EF 4.1 Code First Detaching Entity
Posted
by
Nazaf
on Stack Overflow
See other posts from Stack Overflow
or by Nazaf
Published on 2011-11-26T07:31:33Z
Indexed on
2011/11/26
9:50 UTC
Read the original article
Hit count: 213
entity-framework-4
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!!
© Stack Overflow or respective owner