tags:

views:

195

answers:

2

Given this LINQ to SQL:

using (var db = Database.Context)
{
    var root = (from post in db.Post
                where post.Id == rootPostId
                select post).Single();

    root.LastActivityUtc = DateTime.UtcNow;

    db.SubmitChanges();
}

What will happen if the same record is concurrently being changed by another call to the same method (where this code lives) with the same rootPostId? Will an exception be thrown?

In such an event--concurrency conflict--I'd like to handle it by simple discarding the change so that just one update to LastActivityUtc is submitted instead of both, which will probably have the same value anyway.

A: 

This seems like a good candidate for a stored procedure. Rather than select/update, create a simple stored procedure that executes the following:

UPDATE Post SET LastActivityUtc = GETUTCDATE() WHERE Id=@id

Pass the id to the stored procedure and call it whenever you want to update the last activity of the post.

Randolpho
The whole point of using LINQ to SQL, at least for me, is to avoid having to create a stored procedure. I'm not using Architect Edition of VS, so I'd rather not open SQL Management Studio. Go ahead, call me lazy. :)
Chris
Ok, you're lazy.I'm not a big fan of stored procedures either, but they have their place, and this sort of quick-change is exactly what they're good for. Use the right tool for a job. LINQ to SQL is a very big hammer. Not everything is a nail.
Randolpho
+2  A: 

You can detect and resolve your concurrency issues, by catching a ChangeConflictException:

using (var db = new MyDataContext())
{
    var root = (from post in db.Post
                where post.Id == rootPostId
                select post).Single();

    root.LastActivityUtc = DateTime.UtcNow;

    try
    {
        db.SubmitChanges();
    }
    catch (ChangeConflictException)
    {
        db.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges);
        db.SubmitChanges();
    }
}

With RefreshMode.KeepChanges you will keep all changes of your client objects, and the changes from other users on other fields will be merged.

Recommended articles:

CMS