Saving a single object instead of the whole context

I came across a scenario where I essentially needed to write the changes to the one-to-many child relationship object to the database, but not save the changes made to the parent object.

Entity Framework is currently engaged in database transaction in context context (EntityContext.SaveChanges ()), which makes sense to enforce relationships, etc. But I wonder if there is any good practice, or perhaps the recommended way on how to make a fine-grained database, recorded in separate languages, not the whole context.

+3
source share
3 answers

? , , " !"?

, ObjectContext, .

, ObjectContext . , .

+7

. , , , , . SaveChanges() , , SaveChanges().

, . , , . , , , .

, , - // , , , , , . .

+4

This can be done using AcceptAllChanges ().

Make your changes to the parent object, call AcceptAllChanges (), then make changes to the related objects and call SaveChanges (). Changes made to parents will not be saved because they were "bound" to the object but not saved to the database.

using (AdventureWorksEntities adv = new AdventureWorksEntities())
{
     var completeHeader = (from o in adv.SalesOrderHeader.Include("SalesOrderDetail")
                             where o.DueDate > System.DateTime.Now
                             select o).First();
     completeHeader.ShipDate = System.DateTime.Now;
     adv.AcceptAllChanges();
     var details = completeHeader.SalesOrderDetail.Where(x => x.UnitPrice > 10.0m);
     foreach (SalesOrderDetail d in details)
     {
          d.UnitPriceDiscount += 5.0m;     
     }
          adv.SaveChanges();
}
+2
source

Source: https://habr.com/ru/post/1715556/


All Articles