views:

101

answers:

3

I'm using LINQ to SQL in ASP.NET MVC. I wrote some new code to update Orders in our system, and as far as I can tell it's exactly like a hundred other similar pieces of code I've written (grab the object, update some fields, submit changes).

This time though, when I try to run the update, I get a "Row not found or changed" LINQ exception on this call stack:

System.Data.Linq.dll!System.Data.Linq.DataContext.SubmitChanges(System.Data.Linq.ConflictMode failureMode) + 0x14c bytes    
System.Data.Linq.dll!System.Data.Linq.DataContext.SubmitChanges() + 0x14 bytes

If I just refresh the page after the exception, it just works with no issues.

How can I get it to work correctly the first time?

I've seen answers on the net relating to DateTime precision and Update checks, but nothing about the submission simply working the second time, not the first.

My code is basically like this:

Order order = myDataContext.Orders.SingleOrDefault(order.OrderID == orderID);
order.Field1 = true;
order.Boolean2 = true;
order.Double1 = 300.0;
myDataContext.SubmitChanges();
A: 

Your code looks fine.

There must be something else in myDataContext that is causing the problem.

Where is myDataContext defined? I am guessing that there is some code in a if is postback block, or something similar, to cause the code that runs to take a different path.

Shiraz Bhaiji
My data context was generated completely by LINQ, except for an additional constructor that I added. I did solve this problem, I'll post below.
Freewalker
+1  A: 

The issue turned out to be that I was changing a related table in between fetching the Order, editing, and saving it.

When the related table was changed, the Order table was indirectly changed because of the parent-child relationship. That caused the change checking validation to fail.

All I needed to do is pull all the related code (fetch, change, save) into one tight block, with no other code in-between. I'm not having any problems now.

Freewalker
This might be the problem: [http://stackoverflow.com/questions/663822/changeconflictexception-in-linq-to-sql-update]
Kris
Kris, checked it out, looks like my issue is different though. The nocount property isn't set on my databases. Thanks for the suggestion.
Freewalker
A: 

Are you creating a new datacontext when rebinding (after calling SubmitChanges)?

You should never reuse a datacontext for selecting, after performing insert/update/delete actions with it.

Sander Rijken
Yeah - after submitting the function exits, so there's no reuse of the datacontext.
Freewalker