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

p.c*_*ell 15 c# datacontext concurrency 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();                
Run Code Online (Sandbox Code Playgroud)

DuplicateKeyException: Cannot add an entity with a key that is already in use.

替代文字

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

次优解决方案

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

Jus*_*ren 23

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

该帖子底部的一个晦涩的评论说:

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

让我知道它是如何为你工作的,因为那篇文章的OP说它为他制定了......