Attach() 的 LINQ To SQL 异常:无法添加具有已在使用的键的实体
考虑这种典型的断开连接场景:
- 使用 LINQ To SQL 从 SQL Server 加载 Customer 对象
- ,用户编辑实体,表示层发回修改后的实体。
- 使用 L2S 的数据层必须将更改发送到 SQL Server
考虑此 LINQ To SQL 查询,其目的是获取 Customer 实体。
Cust custOrig = db.Custs.SingleOrDefault(o => o.ID == c.ID); //get the original
db.Custs.Attach(c, custOrig); //we don't have a TimeStamp=True property
db.SubmitChanges();
DuplicateKeyException:无法添加具有已在使用的密钥的实体。
问题
- 如何避免这种异常?
- 更新没有/想要/不需要时间戳属性的实体的最佳策略是什么?
次优解决方法
- 手动将更新客户中的每个属性设置为原始客户。
- 启动另一个 DataContext
Consider this typical disconnected scenario:
- load a Customer object from SQL Server using LINQ To SQL
- user edits the entity, and the presentation tier sends back the entity modified.
- the data layer, using L2S, must send the changes to SQL Server
Consider this LINQ To SQL query whose intention is to take a Customer entity.
Cust custOrig = db.Custs.SingleOrDefault(o => o.ID == c.ID); //get the original
db.Custs.Attach(c, custOrig); //we don't have a TimeStamp=True property
db.SubmitChanges();
DuplicateKeyException: Cannot add an entity with a key that is already in use.
Question
- How can you avoid this exception?
- What's the best strategy for updating an entity that does NOT have/want/need a timestamp property?
Sub-Optimal Workarounds
- manually set each property in the updated customer to the orig customer.
- spin up another DataContext
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这与您的数据上下文(db)无法多次跟踪同一实体有关。有关所发生情况的更多详细信息,请参阅这篇文章。
该帖子底部的一条晦涩评论说要尝试:
让我知道它对你来说效果如何,正如该帖子的 OP 所说,这对他来说效果很好......
This has to do with the fact that your datacontext (db) cannot track the same entity more than once. See this post for more details on what's going on.
One of the obscure comments at the bottom of that post says to try:
Let me know how it works out for you, as the OP of that post says it worked out for him...
您可以这样做,而不是创建新的上下文:
Instead of creating a new context you could do this: