如何正确地将集合保存到实体中?
我有一些里面有 EntityCollection 的对象。 如果我只是添加新实体,一切都会很好。此处执行此操作的代码:
Context.ApplyChanges()
Context.SaveChanges()
但是如果我尝试更新实体,则会收到以下消息:
AcceptChanges 无法继续,因为 对象的键值冲突 中的另一个对象 对象状态管理器。确保 调用前键值是唯一的 接受更改。
即使使用相同的集合对象。我的意思是集合中不可能存在真正相同的实体对象,因为如果它们是新的,则会将其保存到数据库中。但!如果我尝试将相同的代码应用于集合中的单独实体,它们将被保存,但如果我尝试将其应用于对象(容器),则会出现此错误。
感谢您的帮助
I have some object with EntityCollection inside.
If I just add the new entity everything works good. The code that does it here:
Context.ApplyChanges()
Context.SaveChanges()
But if I try to update the entity I have the following message:
AcceptChanges cannot continue because
the object's key values conflict with
another object in the
ObjectStateManager. Make sure that the
key values are unique before calling
AcceptChanges.
Even if use the same collection objects. I mean there can not be real the same entity objects in the collection because are saved into database if they are new. But! If I try to apply the same code to the separate entities into collection they are saved but again if I try to apply it on the object (container) I have this error.
Thanks for the help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否尝试过从
Context
检索您想要更改的实体,适当地修改该实体,然后保存更改?如果是这样,您能提供一个更详细的例子吗?Have you tried retrieving the entity you wish to change from the
Context
, modifying that entity appropriately, then saving changes? If so, could you provide a more detailed example?我怀疑您在模型或表架构中遗漏了某些内容。如果模型主键应该自动生成,那么这就是我所期望的,但是您的表/模型代码没有这样定义它。然后,您会将集合中对象的所有主键设置为零,并且在尝试插入第二个对象时会遇到主键冲突。
I suspect you've omitted something from your model or your table schema. This is what I would expect if the model primary key was expected to be autogenerated, but your table/model code doesn't define it that way. You'd then have all the primary keys for the object in the collection set to zero and you get a primary key violation when attempting to insert the second object.