Cloning Object with many-to-many relationship in EntityFramework

自作多情 提交于 2019-12-06 07:55:06

You can use the fact that adding an object to a context changes the state of any child objects in its object graph to Added:

Project proj;
using (var db = new MyDbContext())
{
    // Fetch a detached project and populate its BusinessRequirements.
    proj = db.Projects.AsNoTracking().Include(p => p.BusinessRequirements)
             .First(p => p.Id == source.Id);
    db.Projects.Add(proj);
    db.SaveChanges();
}

By fetching the source project with AsNoTracking the context does not add it to its change tracker and the next line db.Projects.Add(proj); considers the project and its adhering child objects as brand new.

Silently, I renounced your strategy to work with one static context. It's a different topic, but you should not do that. Contexts are supposed to have a short life span.

The problem exists due to the way you are copying the BusinessRequirement. You are just adding references from the source to the target. So each BusinessRequirement end up with a reference to both Projects.

You need to do something like this.

    target.BusinessRequirements = new List<BusinessRequirement>();
         foreach(BusinessRequirement br in source.BusinessRequirements)
         {
           BusinessRequirement obr = DataLayer.Get<BusinessRequirement>(s=>s.Id=br.Id).SingleOrDefault();
BusinessRequirement obr = new BuisnessRequirment();
            if(nbr!=null){
//copy protperies in obr to nbr
}
              target.BusinessRequirements.Add(nbr);
         }  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!