Problem with SaveChanges() Entity Framework 4.1

懵懂的女人 提交于 2019-12-06 06:01:52

That is common behavior. The problem is that EF doesn't know that you attached an existing B so it automatically inserts a new record. You must say EF that the B is existing one by calling:

// here add B to the collection in the A and after that call:
dbContext.Entry<B>(someB).State = EntityState.Unchanged();

or by attaching B before you add it to collection in A (I'm not sure if this is possible when using UpdateModel in ASP.NET MVC).

dbContext.Bs.Attach(someB);
// now add B to the collection in the A

Other possibility is to load B from database first and add loaded object to the collection in A but it is additional roundtrip to database.

int id = someB.Id;
var loadedB = dbCotnext.Bs.Single(b => b.Id == id);
someA.Bs.Add(loadedB);
dbContext.As.Add(someA);
dbContext.SaveChanges();

Conclusion: Every time you call Add the whole object graph is tracked as inserted unless you attach related entities first (before you add them to inserted parent - the 2nd and 3rd example) or unless you manually change the state of related entities back to unchanged after adding the parent. (the 1st example).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!