c# - An entity object cannot be referenced by multiple instances of IEntityChangeTracker EF 6 -


i developing application in mvc 5 , ef 6. using generic method update entity , extension method detect changed values , properties. when try insert updated record, got error,

an entity object cannot referenced multiple instances of ientitychangetracker

my code update is:

public void update(t data) {     var originalentity = db.set<t>().asnotracking().firstordefault(e => e.id == data.id);     var modifiedvalues = originalentity.modifiedvalues<t>(data).tolist();     (int = 0; < modifiedvalues.count; i++)     {        string modifiedfield = modifiedvalues.elementat(i).key;        string modifiedvalue = modifiedvalues.elementat(i).value.tostring();        propertyinfo prop = data.gettype().getproperty(modifiedfield, bindingflags.public | bindingflags.instance);        string s = prop.propertytype.generictypearguments.select(x => x.fullname).singleordefault();        switch (s)        {             case ("system.datetime"):             {                 datetime d = convert.todatetime(modifiedvalue);                 prop.setvalue(data, d);                 break;             }             case ("system.string"):             {                 prop.setvalue(data, modifiedvalue);                 break;             }        }    }    insert(data); // error occurred in function    save();     } 

the code insert function is:

public void insert(t data) { db.set<t>().add(data); } 

at statement db.set().add(data);, error occurred.

i know occurs when entity attached context. in these functions use context object db once asnotracking(), error shouldn't occur.

i looked answer in this question , modify update function as:

db.entry(data).state = entitystate.detached; insert(data); // error again occurred in function save();  

but error still occurs. problem? how can solve it?

i call update function controller:

private baserepository<abc> g = new baserepository<abc>(); abc m = new abc(); m = db.abcs.find(id); m.s107 = "2"; m.d103 = datetime.now; m.s36 = "awais"; g.update(m); 

you using m = db.abcs.find(id);, attaches entity context.

try exchanging db.abcs.asnotracking().where(abc => abc.id == id).first();

from dbset.find documentation:

... request made store entity given primary key values , entity, if found, is attached context , returned. ...


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -