c# - Entity loaded twice in same Context, InvalidOperationException -
i have db-first entity framework application , following associations:
customer * <-> 1 country machine * <-> 1 customer   everything fine until now. here problem:
 have class condition associated machine customer:
condition * <-> 1 customer condition * <-> 1 machine   in 1 special entity condition.machine.customer.country same entity condition.customer.country , invalidoperationexception message 
an object same key exists in objectstatemanager
this exception appears when call
db.entry(condition).state = entitystate.modified;   also country entites unchanged exception.  
how can store condition entity?
if working in disconnected context can't rely on ef trackchanges mechanism, , graph relationships context saving in has no way of knowing whether child new/updated/no-change. when come save changes error you're seeing because child entity exists , ef attempting add again.
julie lerman has method involves managing own modified state, can correctly attach/detach entities needed.
another method shown here: http://www.entityframeworktutorial.net/entityframework4.3/update-one-to-one-entity-using-dbcontext.aspx
this reloads child entity trying save (without tracking), removes parent, , allows mark entity state of parent 'modified' , re-add child if has one.
Comments
Post a Comment