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, , , , ( ).