Instead of saving the complete context, just one entity is saved.

c# entity-framework


I've encountered a situation where I basically need to preserve any changes made to the child entity in a one-to-many relationship but not the parent object.

In order to enforce relationships and other things, the Entity Framework now handles database commits in the context scope (EntityContext.SaveChanges()). However, instead of committing changes to the full context, I'm wondering whether there is a best practice or even a suggested method for executing fine-grained database commits on certain entities.

8/19/2009 5:31:43 PM

Accepted Answer

ideal procedures? Other than, "Don't do it!" do you mean?

Making an ObjectContext distinct from the database's current state is not, in my opinion, a great practice.

If you have to do this, create a new ObjectContext and modify the child entity there. Both contexts are compatible in this sense.

8/19/2009 5:41:28 PM

Popular Answer

Similar needs exist for me. I'm thinking of giving all entities wrapper properties so that they may save any changes to a property privately without impacting the main entity property. I would then add a SaveChanges() function to the entity, call SaveChanges() on the context, and write the changes to the entity.

The drawback of this strategy is that you have to force all of your entities to follow this pattern. But it seems to function rather well. There is one more drawback to it: if you alter a lot of objects with a lot of data, you may wind up with additional copies of those modifications in memory.

The only other option that comes to me is to save the entity states of all new, removed, and altered entities before making the changes, set all except the one you're modifying to unmodified, save the changes, and then restore the states of the other entities. But it may sound too sluggish.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow