c# - How to replace the entity that the objectstatemanager is tracking -


i getting "an object same key exists" on update attempt while trying attach entity.lazy loading turned on. googled, , found no real solution problem. best solution replace entry in object state manager, can not find anywhere how replace it. possible @ all?

the problems occurs when create instance of object (has collection of object b) in 1 context, , b objects in context. when try attach both of them breaks. there way tell ef when replace entry tracking. maybe possible allow replacement when set duplicated entitykey entries objectstate modified.

there 2 parts problem.

1. detecting if entity being tracked context.

if have 2 references same instance of entity easy see if being tracked.

boolean istracked = context.myentities.local.contains(myentity); 

if instead have 2 instances of entity conceptually same because have same key things can more difficult.

boolean istracked = context.myentities.local.any(x=>x.id == myentity.id); 

or alternatively using equalitycomparer<t>:

public class myentityequalitycomparer : equalitycomparer<myentity> {    public override bool equals(myentity x, myentity y)    {       return x.id == y.id;    }     public override int gethashcode(myentity obj)    {       return obj.id;    } }  context.myentities.local.contains(myentity, new myentityequalitycomparer()); 

2. switching out entity being tracked.

this can achieved so:

context.entry<myentity>(entitytoreplace).state = entitystate.detached; context.myentities.attach(entitytoadd); 

however, before should @ application design. having juggle entities between contexts can sign not grouping tasks appropriate units of work operate on single context.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -