c# - Cloning Object with many-to-many relationship in EntityFramework -
all want create exact re-create of object.
i have class
[serializable] public class project { public int id { get; set; } public string name { get; set; } //navigational fields.. public virtual list<businessrequirement> businessrequirements { get; set; } }
and another
[serializable] public class businessrequirement { public int id { get; set; } public string name { get; set; } public string description { get; set; } public virtual list<project> projects { get; set; } }
so somewhere i've configured many-to-many relationship b/w project
, businessrequirement
this:
hasmany(s => s.businessrequirements) .withmany(s => s.projects) .map(m => { m.mapleftkey("projectid"); m.maprightkey("businessrequirementid"); m.totable("projectbusinessrequirementmapping"); });
and i've made dbcontext static i.e.
public static class datalayer { public static mydbcontext db; }
now, m doing is, trying create re-create of object of project
i.e.
public project clone(project source) { project target = new project(); target.name = source.name; //1. // target = source; //2. target.businessrequirements = new list<businessrequirement>(); foreach(businessrequirement br in source.businessrequirements) { businessrequirement nbr = datalayer.get<businessrequirement>(s=>s.id=br.id).singleordefault(); if(nbr!=null) target.businessrequirements.add(nbr); } //3. //target.businessrequirements = source.businessrequirements; //4. //target.businessrequirements = new list<businessrequirement>(); //foreach(businessrequirement br in source.businessrequirements) //{ // businessrequirement nbr = br; // if(nbr!=null) // target.businessrequirements.add(nbr); //} homecoming target; }
none of 4 methods work properly.
the 1 closest working 2, unusual thing happens. now, if add together businessrequirements original project
, gets added clonned one
, vice-versa, same goes deletion.
somehow, entityframework treating both projects one. though behavior occurs in many-to-many related navigational properties.
why entityframework behaving this???. missing? please help..
its been day, cannot work.
i have tried this, this, this , this didn't work either..
you can utilize fact adding object context changes state of kid objects in object graph added
:
project proj; using (var db = new mydbcontext()) { // fetch detached project , populate businessrequirements. proj = db.projects.asnotracking().include(p => p.businessrequirements) .first(p => p.id == source.id); db.projects.add(proj); db.savechanges(); }
by fetching source project asnotracking
context not add together alter tracker , next line db.projects.add(proj);
considers project , adhering kid objects brand new.
silently, renounced strategy work 1 static context. it's different topic, should not that. contexts supposed have short life span.
c# linq clone entity-framework-5
No comments:
Post a Comment