实体框架 4.1 修改对象和子集合
如果我有 Book 对象,其中包含 Comments 子集合,我可以与实体框架一起更新 Book 和 Comments 列表吗?
我尝试过:
_context.Books.Attach(book);
_context.ObjectStateManager.ChangeObjectState(book, EntityState.Modified);
_context.SaveChanges();
但没有运气...
在第一行出现以下错误:
ObjectStateManager 中已存在具有相同键的对象。 ObjectStateManager 无法跟踪具有相同键的多个对象
If I have Book object which has a child collection of Comments, Can I update the Book and list of Comments together with entity framework?
I have tried :
_context.Books.Attach(book);
_context.ObjectStateManager.ChangeObjectState(book, EntityState.Modified);
_context.SaveChanges();
with no luck...
getting the following error on the first line:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您很可能存在循环依赖(书籍有对评论的外键引用,评论又回到书籍)。在这种情况下,EF 内的 UpdateTranslator 无法确定依赖顺序。据我所知,在这种开发模型中,没有办法向 EF 传递提示来指示顺序是什么。
解决这个问题的最常见方法(我见过)是进行两阶段提交。对书籍进行更改并保存,然后对评论进行更改并保存。我发现使用 代码优先方法允许您更具体地了解关系,从而解决我遇到的许多问题。
编辑:
下面是一个示例:
如果存在循环依赖项,则无法通过单次调用
SaveChanges
来完成上述操作。More than likely you have a circular dependency (Books has a foreign key reference to Comments, and Comments back to Books). In this case, the UpdateTranslator within EF is unable to determine the dependency order. As far as I can tell, in this model of development, there is no way to pass a hint to EF to indicate what the order is.
The most common way to solve this (that I have seen) is to do a two-phase commit. Make a change to the Book, save it, then make a change to Comments, and save that. I have found that using the Code First approach allows you to be more specific about the relationships and thereby fix many of the problems that I've had.
Edit:
Here's an example:
If there is a circular dependency, you could not do the above with a single call to
SaveChanges
.