There is no way. It is limitation of EF. Your options are.
Up vote 0 down vote favorite share g+ share fb share tw.
I am trying to add an entity to the DB. Once I have added it, I want to detach it, so I can manipulate the object safely without making any changes to the DB. After calling context.SaveChanges() I do the following to detach the entity: // save context.Stories.
Add(story); // attach tags. They already exists in the database foreach(var tag in story. Tags) context.
Entry(tag). State = System.Data.EntityState. Unchanged; context.SaveChanges(); context.
Entry(story). State = System.Data.EntityState. Detached; However, changing the entity state to DETACHED will remove all related entities associated with the my entity.
Is there a way to stop this? If I don't detach the entity, all my changes are sent to the DB next time I call context.SaveChanges() Thanks! Entity-framework-4 ef-code-first link|improve this question edited Nov 26 '11 at 7:37 asked Nov 26 '11 at 7:31Nazaf520411 86% accept rate.
There is no way. It is limitation of EF. Your options are: Not using the same context for another save (single context instance = single save) Retrieve the entity from database again using another context instance which will not be used for saving Create deep clone of your entity and use the clonned one (deep clone is done by serialization and immediate deserialization = your entity graph must be serializable).
Thanks. I created a clone of the entity and used the cloned one. – Nazaf Nov 26 '11 at 18:20 Retrieving the entity again is not efficient at all.
Using a different context is not easy either. – Nazaf Nov 26 '11 at 18:21.
I think there are two ways to approach this problem: Purist: retrieving entities from a DbContext and modifying them without saving is a misuse of the tools and the architecture. Use a DTO instead. Pragmatic: you can use AsNoTracking() to retrieve an entity graph that will not be tracked by the context for changes.
AsNoTracking() is for retrieving, not for adding entities. Modifying entities without saving is not a misuse. Sometimes, you need to tweak values in the presentation layer without saving to the DB.
– Nazaf Nov 26 '11 at 18:23 OK, I didn't read the first part correctly. Still, "tweaking values in the presentation layer" is what a ViewModel is for. – Diego Mijelshon Nov 26 '11 at 21:06.
I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.