How can I increase the number of page views using linq-to-sql?

I have an ASP.NET MVC 3 web application using Linq-to-SQL for my data access level. I try to increase the Views field every time the Details action is called, but I get a "Row not found or changed" error on db.SubmitChanges () if two people get into the action at the same time.

public ActionResult Details(int id)
{
    DataClassesDataContext db = new DataClassesDataContext();

    var idea = db.Ideas.Where(i => i.IdeaPK == id).Single();

    idea.Views++;

    db.SubmitChanges();

    return View(new IdeaViewModel(idea));
}

I can set UpdateCheck in the Views field to "Never" in my .dbml (Data Model), which will get rid of this error, but then the idea record can be updated twice with the same number of views. i.e.

First instance of Details action gets idea record with Views count of 1.
Second instance of Details action gets idea record with Views count of 1.
First instance increments Views to 2
First instance commits
Second instance increments Views to 2
Second instance commits

Result: Views field is 2 
Expected Result: Views field should be 3

I learned using TransactionScope, but I got the following deadlock error from one of two calls:

( 54) . .

, :

public ActionResult Details(int id)
{
    DataClassesDataContext db = new DataClassesDataContext();

    using (var transaction = new TransactionScope()){
        var idea = db.Ideas.Where(i => i.IdeaPK == id).Single();

        idea.Views++;

        db.SubmitChanges();

        return View(new IdeaViewModel(idea));
    }
}

- TransactionScope TransactionScopeOptions , , ( , , ). , , , SQL, db.ExecuteQuery, , , , ( ).

+5
5

. DataContext.ExecuteCommand:

db.ExecuteCommand("UPDATE Ideas SET Views = Views + 1 WHERE IdeaPK = {0}", id);

SQL , , .

+2

, , LINQ2SQL.

.

+4

Row not Found . . , , , .

+1

, @Dmitry, . : 1) 2) . :

CREATE PROCEDURE spIdeasRetrieveAndLog
    @IdeaPK int
AS
BEGIN
    UPDATE Ideas SET Views = Views + 1 WHERE IdeaPK = @IdeaPK
    GO
    SELECT * FROM Ideas WHERE IdeaPK = @IdeaPK
END
GO
+1

(, NServiceBus, - MassTransit, Rhino Service Bus). .

+1

All Articles