I ran into an interesting issue with LINQ to SQL yesterday. I had to update a table with no Primary Key. As I expected, LINQ to SQL wasn’t too happy with this scenario. Unfortunately LINQ to SQL will only throw an exception when you try to Insert or Delete a record with no primary key. Updates fail silently.
It’s actually quite obvious when you look into what is happening. To do an update you would usually do something like this:
1 2 3 4 5 |
|
Of course, nothing happens. Here’s the code (slightly edited for readability) that is generated by the LINQ to SQL classes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
|
Without a primary key the two following interfaces aren’t emitted:
INotifyPropertyChanging
and INotifyPropertyChanged
Therefore LINQ to SQL doesn’t know that your record has changed (so can’t warn you that it can’t update).
Now that you understand the problem the solution is simple: Define a primary key in your table.