简体   繁体   中英

Why does LINQ to SQL report a conflict on Windows Phone, when the database doesn't appear to have one?

I've got a web service that is returning objects for me, along with a candidate key, which I've marked up with:

[Column(IsPrimaryKey = true)]
public int EventId { get; set; }

All is fine with loading the data back from the webservice, but whilst iterating through the new & updated items to put them in a SQL CE database to act as a cache, like so:

foreach (var e in results)
{
    var ev = (from evt in context.Events where evt.EventId == e.EventId select evt).FirstOrDefault();
    if (ev == null)
    {
        // Brand new
        context.Events.InsertOnSubmit(e);
    }
    else
    {
        // Update data
        ...
    }
}

For some reason, it occasionally thinks an event is brand new but it throws an exception during the InsertOnSubmit :

System.InvalidOperationException was unhandled

Cannot add an entity that already exists.

I've pulled the database off of the emulator with the Windows Phone Power Tools, loaded the database up in Visual Studio, and there doesn't seem to be any conflicting value for the primary key, so why am I getting an exception that implies there is a conflict, and the debugger shows there aren't any cross-thread issues?

EDIT

One thing I did spot, is that my entity has an overridden Equals() that didn't cover the primary key (it did a comparison on a natural key), and it appears the web service has two records on something that is documented as a candidate key.

If I adjust the Equals method to account for the primary key as well, the exception changes to be a SqlCeException and it tells me that:

A duplicate value cannot be inserted into a unique index. [ Table name = SpecialEvent,Constraint name = PK_SpecialEvent ]

Even though the primary key still hasn't been duplicated, which leaves me more confused (especially, as that type of exception cannot be easily caught)

EDIT2

I've even tried using a lock() {} around the code performing the update, but I'm still getting odd conflicts, so I'm confused why I'm occasionally getting conflicts, especially when the SDF doesn't reflect the same conflicts.

In my case, it turns out that it was down to a couple of factors combining -- my entities did not have a property with IsVersion = true nor did they have UpdateCheck = UpdateCheck.Never on columns that did not make up part of my primary key. It appears there was a timing issue which was resulting in it trying trying to update only when the columns matched what it was expecting the old values to be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM