views:

378

answers:

2

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.

A: 

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.

Craig Stuntz
Using a seperate context is a good way to do it. Process is basically: 1) Create another ObjectContext and attach attach the child object there 2) Set the EntityKey of the parent navigation property 3) Save the new context and then detach the child 4) Attach the child to the "main" context
dkr88
A: 

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();
}
Dave Swersky
Makes sense - but then if I still needed to track and then committ the changes to the parent object I'd lose the ability to do that after doing AcceptAllChanges() (correct?)
dkr88