下面试图更新数据库中的一行列出的代码中DuplicateKeyException,但不是抛出一个异常:的LINQ to SQL - 更新
System.Data.Linq.DuplicateKeyException: Cannot add an entity with a key that is already in use
大多数例子我见过的查询数据库获取的实例一个实体,修改一些实例的属性,然后更新它。在这里我从不同的来源获取对象完全(它正在从一个XML文件解析)和查询,看是否已经存在该数据的行。如果有,我正在设置主键并尝试运行更新。什么是正确的方法来做到这一点?
下面的代码的下调版本:
Customer customer = new Customer(); // Customer has a database generated
// identity column called CustomerId
// populate customer object
customer.Name = "Mr. X";
customer.Email = "[email protected]";
// etc.
// is customer already in database?
// identify customer by email
var results = ctx.Where(c => c.Email == customer.Email); // ctx is a DataContext
if (results.Any())
{
Customer existing = results.Single();
// set primary key to match existing one
customer.CustomerId = existing.CustomerId;
// update database
customerTable.Attach(customer); // customerTable is a Table<Customer>
ctx.SubmitChanges();
}
// otherwise do insert
// ...
有趣。我猜这就是我所建议的(但在代码中)。你能否更多地解释一下LINQ to SQL的新手如何工作? – JasCav 2010-06-30 15:43:02
我试过了。它给了我同样的错误。 – MCS 2010-06-30 15:43:10
在我看来,customerTable.Attach(客户,现有)也应该有效。但是,如果我没有设置customer.CustomerId,我得到的错误:System.InvalidOperationException:类型为'Customer'的对象的成员'CustomerId'的值发生了变化。定义对象身份的成员不能更改。当我设置Customer.CustomerId时,我得到了DuplicateKeyException!去搞清楚。 – MCS 2010-06-30 17:26:25