tags:

views:

41

answers:

2

Do I have to refresh a LINQ object that represents a view/table row after I do a submitchanges operation that may alter it?

Let's say I have

Event _event = new Event
{
someproperty = "this";
};

DataContext.Events.InsertOnSubmit(_event);

DataContext.SubmitChanges();

//some operations

_event.someproperty = "that";
DataContext.SubmitChanges();

Let's add to the equation that during some operations, a different thread, with a different instance of DataContext, might change the same _event and submit it.

I sometimes get an exception saying the row cannot be found or has changed. Is there a way to get around this without me having to reselect the _event?

+1  A: 

If the entities are in the same DataContext, you don't, but if you have additional Datacontexts accessing the data (eg from other processes) then you need to be aware and refresh before you try commit.

Doobi
+2  A: 

I suppose you use optimistic concurrency with Linq. That means when updating an object in the DB, the update statement checks that the row was not changed in the meantime.

If another process changed the object in the DB between your initial read (or creation) of the object and your update, Linq will throw a ChangeConflictException. You can catch this Exception and handle the conflict (by reloading the object from the DB or by overwriting the DB values).

More details here: http://msdn.microsoft.com/en-us/library/bb399373%28v=VS.90%29.aspx

Your code could look something like:

try
{
_event.someproperty = "that";
DataContext.SubmitChanges();
}

catch (ChangeConflictException e)
{
    foreach (ObjectChangeConflict occ in db.ChangeConflicts)
    {
        // All database values overwrite current values.
        occ.Resolve(RefreshMode.OverwriteCurrentValues);
    }
}

There are several refresh modes and it really depends on how you want your application to behave. Please find more details in these answers:

PeterTheNiceGuy