Quantcast
Viewing latest article 3
Browse Latest Browse All 15

Row Not Found Or Changed LINQ to SQL Error

You may have gotten this error when trying to update data, as I recently did.  After reading up on the subject, I found this which helped:   http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/2bb60aae-7510-4eae-846b-1dad25f2f181

By establishing a log for the data context, I figured out what the issue was.  LINQ to SQL attempts to get the current object by retrieving all of the information using the previous values that weren't changed.  So if you have a 15 column table, and two values changed, LINQ to SQL attempts to find the record using the 13 unchanged values, and performing the update on the other 2, as something like:

update [dbo].Table1 set Field1 = @p13, Field2 = @p14 where Field3 = @p0 and Field4 = @p1 and ... [and so on]

So if something changed about one of those thirteen values, it won't find the record and an error will occur.  This is what I was doing; I posted recently about an issue with an exception being thrown when the foreign key already has the value.  If you have a PK reference as an EntityRef<>, if that reference is loaded, you cannot change it.  You can if you add a method to it that does:

public void ClearReference()
{
     _SomeType = default(EntityRef<SomeType>);
}

This actually clears the reference.  You can't do obj.SomeType = null because it detects the value has changed (even though its being set to null) and the exception still ensued.  So I originally was clearing both the key and the type, setting both to null.  Setting the key causes Row not found error because the original key no longer exists and it looks for a null check.  And thus, one of the 13 original values was changed without LINQ to SQL knowing it, and an error ensued.

Because I actually have to clear the variable, and not the property reference, I don't know if an extension method can be used to clear it; it is something I'm going to investigate.

Image may be NSFW.
Clik here to view.

Viewing latest article 3
Browse Latest Browse All 15

Trending Articles