【发布时间】:2010-06-30 15:32:48
【问题描述】:
下面列出的代码尝试更新数据库中的一行,但会引发异常:
System.Data.Linq.DuplicateKeyException: 无法添加具有以下键的实体 已经在使用中了
我见过的大多数示例都查询数据库以获取实体的实例,修改实例的一些属性,然后对其进行更新。在这里,我完全从不同的源获取对象(它是从 XML 文件中解析的)并查询是否已经存在该数据的行。如果有,我正在设置主键并尝试运行更新。这样做的正确方法是什么?
这是代码的精简版:
Customer customer = new Customer(); // Customer has a database generated
// identity column called CustomerId
// populate customer object
customer.Name = "Mr. X";
customer.Email = "x@company.com";
// 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
// ...
【问题讨论】:
标签: c# linq-to-sql