Attach() 的 LINQ To SQL 异常:无法使用已在使用的键添加实体 [英] LINQ To SQL exception with Attach(): Cannot add an entity with a key that is already in use

查看:39
本文介绍了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);//获取原件db.Custs.Attach(c, custOrig);//我们没有 TimeStamp=True 属性db.SubmitChanges();

<块引用>

DuplicateKeyException:无法使用已在使用的密钥添加实体.

问题

  • 如何避免这种异常?
  • 更新没有/想要/不需要时间戳属性的实体的最佳策略是什么?

次优解决方法

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

解决方案

这与您的数据上下文 (db) 不能多次跟踪同一个实体有关.请参阅这篇文章,了解有关正在发生的事情的更多详细信息.

该帖子底部的一条晦涩的评论说要尝试:

public void Update(Customer customer){NorthwindDataContext context = new NorthwindDataContext();上下文.附加(客户);context.Refresh(RefreshMode.KeepCurrentValues, customer);context.SubmitChanges();}

让我知道它对你有什么作用,因为那个帖子的 OP 说它对他有用......

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

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆