LINQ to SQL Concurrency – ChangeConflictException Row not found or changed

25 בנובמבר 2007

LINQ to SQL Concurrency – ChangeConflictException Row not found or changed

ChangeConflictException Row not found or changed If we create a small model of the Northwind database, and we try to modify one of the customers (lets take ALFKI for example):

NorthwindDataContext db = new NorthwindDataContext();

 

Customer alfki = db.Customers.Single(c => c.CustomerID == "ALFKI");

alfki.City = "London";

 

db.SubmitChanges();

We will see that the update command that is created by the run time is:

UPDATE   Customers

SET      City = 'London'

WHERE    CustomerID = 'ALFKI' AND

         CompanyName = 'Alfreds Futterkiste' AND

         City = 'Berlin' AND

         Region IS NULL

Of course, the update command updates the City column in the Customers table according to the appropriate CustomerID value, but what with all these other conditions in the where clause?

LINQ to SQL uses Optimistic Concurrency strategy. When it selects records, it does not perform any locking on the selected rows. Only when it tries to update records in the database or delete them, it checks that the records were not changed since the last time they were selected. How does it do it? It tries to update the row that matches the original values, as the DataContext got them when it selected the rows. This explains the additional conditions on the update command.

If during the time the logic was done, updates were made from another program (or another DataContext for that matter), an exception will be thrown:

System.Data.Linq.ChangeConflictException was unhandled
  Message="Row not found or changed."
  Source="System.Data.Linq" 

LINQ to SQL tried to look for the record to updated comparing all the columns to their original values, and when no records where found, the exception was thrown. This is the way LINQ to SQL tells us that the row it was looking for was deleted or changed by another program and the update cannot be done.

Enjoy!

Add comment
facebook linkedin twitter email

4 comments

  1. Gazz20 בינואר 2009 ב 16:24

    You're a saint!!!! I had a problem with the "Row not found or changed" and went on a wild goose chase around all my date fields… Found out that it was a string field in the database that accepted nulls. So the generated sql was trying to check a null database value against a blank string!

    Thanks for the post.

  2. Richard1 בספטמבר 2009 ב 16:29

    This can happen if strings in your Database allow NULL, but your DBML file variables do not.

  3. Ali28 ביולי 2011 ב 5:19

    Check to see if time stamp field in the DBML Designer for the particular entity that you having problem with has Time Stamp property to false. Thats how I got rid of the error.

Comments are closed.