Saving a single entity instead of the entire context

16,207

Solution 1

Best practices? Do you mean, besides, "Don't do it!"?

I don't think there is a best practice for making an ObjectContext different than the state of the database.

If you must do this, I would new up a new ObjectContext and make the changes to the child entity there. That way, both contexts are consistent.

Solution 2

I have a similar need. The solution I am considering is to implement wrapper properties on all entities that store any property changes privately without affecting the actual entity property. I then would add a SaveChanges() method to the entity which would write the changes to the entity and then call SaveChanges() on the context.

The problem with this approach is that you need to make all your entities conform to this pattern. But, it seems to work pretty well. It does have another downside in that if you make a lot of changes to a lot of objects with a lot of data, you end up with extraneous copies in memory.

The only other solution I can think of is to, upon saving changes, save the entity states of all changed/added/deleted entities, set them to unmodified except the one you're changing, save the changes, and then restore the states of the other entities. But that sounds potentially slow.

Solution 3

This can be accomplished by using AcceptAllChanges().

Make your changes to the parent entity, call AcceptAllChanges(), then make your changes to the related Entities and call SaveChanges(). The changes you have made to the parent will not be saved because they have been "committed" to the Entity 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();
}
Share:
16,207
dkr88
Author by

dkr88

Updated on June 08, 2022

Comments

  • dkr88
    dkr88 almost 2 years

    I've run into a scenario where I essentially need to write the changes of a child entity of a one-to-many association to the database, but not save any changes made to the parent entity.

    The Entity Framework currently deals with database commits in the context scope (EntityContext.SaveChanges()), which makes sense for enforcing relationships, etc. But I'm wondering if there is some best practice or maybe a recommended way to go about doing fine-grained database commits on individual entites instead of the entire context.