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

查看:178
本文介绍了LINQ To SQL异常与Attach():无法添加具有正在使用中的键的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑此典型的已断开连接的方案:

Consider this typical disconnected scenario:


  • 使用LINQ To SQL从SQL Server加载Customer对象

  • 用户编辑实体,并且表示层将实体发回修改。

  • 数据层使用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:

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...

这篇关于LINQ To SQL异常与Attach():无法添加具有正在使用中的键的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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