LINQ to SQL的异常,并连接():不能与一个关键是alredy使用添加实体 [英] LINQ To SQL exception with Attach(): Cannot add an entity with a key that is alredy in use

查看:174
本文介绍了LINQ to SQL的异常,并连接():不能与一个关键是alredy使用添加实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这种典型断开的情况:




  • 从使用LINQ to SQL的SQL Server加载一个Customer对象

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

  • 数据层,使用L2S,必须将这些更改发送到SQL Server



考虑这个LINQ to SQL查询,其目的是采取Customer实体。

 卡斯特custOrig = db.Custs.SingleOrDefault(O => o.ID == c.ID); //获取原
db.Custs.Attach(C,custOrig); //我们没有时间戳= true属性
db.SubmitChanges();




DuplicateKeyException:不能用增加一个实体密钥已被使用。









  • 您如何避免此异常?

  • 什么是更新不具有/想/需要一个时间戳记属性的实体的最佳策略是什么?



次优解决办法




  • 手动设置每个属性在更新的客户对原稿客户。

  • 旋转起来另一个DataContext的


解决方案

这是与事实,你的datacontext(DB)无法跟踪相同的实体不止一次做。请参见对正在发生的事情更多的细节这篇文章



一个在该职位的底部不起眼的评论说尝试:

 公共无效更新(客户客户)
{
NorthwindDataContext上下文=新NorthwindDataContext();
context.Attach(客户);
context.Refresh(RefreshMode.KeepCurrentValues​​,客户);
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...

这篇关于LINQ to SQL的异常,并连接():不能与一个关键是alredy使用添加实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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