带有Attach()的LINQ To SQL异常:无法添加具有已在使用的键的实体 [英] LINQ To SQL exception with Attach(): Cannot add an entity with a key that is already in use
问题描述
考虑这种典型的断开连接的情况:
Consider this typical disconnected scenario:
- 使用LINQ To SQL从SQL Server加载客户对象
- 用户编辑实体,表示层将修改后的实体发回.
- 使用L2S的数据层必须将更改发送到SQL Server
考虑此LINQ To SQL查询,其目的是采用一个Customer实体.
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.
问题
- 如何避免这种例外情况?
- 更新没有/想要/不需要时间戳属性的实体的最佳策略是什么?
次优解决方法
- 手动将已更新客户中的每个属性设置为原始客户.
- 启动另一个DataContext
推荐答案
这与以下事实有关:您的数据上下文(db)不能多次跟踪同一实体.请参阅这篇文章,以了解发生了什么事情的更多详细信息.
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:
public void Update(Customer customer)
{
NorthwindDataContext context = new NorthwindDataContext();
context.Attach(customer);
context.Refresh(RefreshMode.KeepCurrentValues, customer);
context.SubmitChanges();
}
让我知道它对您有什么好处,因为该帖子的操作说明说对他有帮助...
Let me know how it works out for you, as the OP of that post says it worked out for him...
这篇关于带有Attach()的LINQ To SQL异常:无法添加具有已在使用的键的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!