使用Attach()的LINQ To SQLexception:无法添加具有已在使用的密钥的实体

考虑这种典型的断开连接情

  • 使用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: Cannot add an entity with a key that is already in use.

替代文字

  • 你怎么能避免这种例外?
  • 更新没有/想要/需要时间戳属性的实体的最佳策略是什么?

次优解决方案

  • 手动将更新的客户中的每个属性设置为orig客户。
  • 启动另一个DataContext

这与您的datacontext(db)不能多次跟踪同一实体的事实有关。 有关正在发生的事情的详细信息,请参阅此post 。

该post底部的一个不起眼的评论说:

 public void Update(Customer customer) { NorthwindDataContext context = new NorthwindDataContext(); context.Attach(customer); context.Refresh(RefreshMode.KeepCurrentValues, customer); context.SubmitChanges(); } 

让我知道它是如何为你工作的,因为那篇文章的OP说它为他解决了……

您可以这样做,而不是创建新的上下文:

 public void Update(Customer customer) { Customer oldCustomer= db.Custs.First(c => c.ID == customer.ID); //retrieve unedited oldCustomer = customer; // set the old customer to the new customer. db.SubmitChanges(); //sumbit to database }