0

I've searched around:

How do I make my Linq to Sql entity implement INotifyPropertyChanged

LINQ-to-SQL class doesn't implement INotifyPropertyChanging & INotifyPropertyChanged if pulling from local database

These answers are not satisfying. They just say add a primary key but I still have no idea why I should have one to have INotifyPropertyChanged implemented, since the data itself doesn't contain any primary key, such that I can use association/foreign key).

During the time I experiment with L2S designer, I found the association code is not generated unless I give a primary key to the table.

I am expecting an answer explaining the reason of such constraint, probably in depth.

Community
  • 1
  • 1
Jason Hu
  • 6,239
  • 1
  • 20
  • 41

1 Answers1

3

The simple answer is that without a primary key, the database would be unable to discern a change in two records with the same exact data in it. What if you changed only one of the two? These types of issues are likely why it is a constraint. What types of events would you expect to be generated if the original table looked like:

col1 col2 col3
test test test

and then on next pass the table looked like this:

col1 col2 col3
test test2 test

Is that a modification of the first record's second column, or is it a delete of one row and an insert of one row?

More complicated:

col1 col2 col3
test test test
test test test

to:

col1 col2 col3
test2 test2 test2
test3 test3 test

Would that be a modification of row1's col1, col2, col3 fields and modification of row2's col1 and col2 fields? Or is it s modification of row1's col1 and col2 fields, and modification of row2's col1, col2, col3 fields? Or is it two rows deleted, 2 rows inserted? Or a combination of insert/delete and modification?

Simple rule is, all tables should have a primary key, always. If there isn't one, then make a primary key out of all the columns, or generate a unique autoincrementing column and make that that primary key. Without one, you can't tell one row from another other than by the data the row contains, and can't track changes (if any) are made to them.

Robert McKee
  • 21,305
  • 1
  • 43
  • 57