开发者

Why do I get a DuplicateKeyException in Linq2Sql after I checked for the keys existence?

开发者 https://www.devze.com 2023-04-08 06:43 出处:网络
I have a program that adds a lot of new data to a database using Linq2SQL. In order to avoid DuplicateKeyExceptions, I check for the existence of the key, before trying to add a new value into the da

I have a program that adds a lot of new data to a database using Linq2SQL.

In order to avoid DuplicateKeyExceptions, I check for the existence of the key, before trying to add a new value into the database.

As of now, I can't provide an isolated test-case, but I have simplified the code as much as possible.

// newValue is created outside of this function, with data read from a file
// The code is supposed to either add new values to the database, or update existing ones

var entryWithSamePrimaryKey = db.Values.FirstOrDefault(row => row.TimestampUtc == newValue.TimestampUtc && row.MeterID == newValue.MeterID);
if (entryWithSamePrimaryKey == null)
{
    db.Values.InsertOnSubmit(newValue);
    db.SubmitChanges();
}
else if(entryWithSamePrimaryKey.VALUE != newValue.VALUE)
{
    db.Values.DeleteOnSubmit(entryWithSamePrimaryKey);
    db.SubmitChanges();
    db.Values.InsertOnSubmit(newValue);
    db.SubmitChanges();
}

Strangely enough, when I look at the exceptions in the application log, as to which items cause troub开发者_运维技巧le, I am unable to find ANY of them in the database.

I suspect this happens within the update code, so that the items get removed from the database, but not added again.

I will update my code to deliver more information, and then update this post accordingly.


If the error is generated in the update block, you can merge the object in the update case without deleting entryWithSamePrimaryKey, but valorizing it with the property value of newValue and than save the changes.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号