linqentity-frameworktransactionsdirtyread

entity framework - does this do a dirty read?


I have a bit of linq to entities code in a web app. It basically keeps a count of how many times an app was downloaded. I'm worried that this might happen:

This is my code:

private void IncreaseHitCountDB()
{
    JTF.JTFContainer jtfdb = new JTF.JTFContainer();

    var app =
        (from a in jtfdb.Apps
         where a.Name.Equals(this.Title)
         select a).FirstOrDefault();

    if (app == null)
    {
        app = new JTF.App();
        app.Name = this.Title;
        app.DownloadCount = 1;

        jtfdb.AddToApps(app);
    }
    else
    {
        app.DownloadCount = app.DownloadCount + 1;
    }

    jtfdb.SaveChanges();
}

Is it possible that this could happen? How could I prevent it?

Thank you, Fidel


Solution

  • You can prevent this from happenning if you only query the download count column right before you are about to increment it, the longer the time spent between reading and incrementing the longer the time another session has to read it (and later rewriting - wrongly - incremented number ) and thus messing up the count.

    with a single SQL query :

    UPDATE Data SET Counter = (Counter+1)
    

    since its Linq To Entities,it means delayed execution,for another session to screw up the Count (increment the same base,losing 1 count there) it would have to try to increment the app.Download count i beleive between the two lines:

        else
        {
            app.DownloadCount += 1; //First line
        }
    
        jtfdb.SaveChanges();  //Second line
    }
    

    thats means that the window for the change to occur, thus making the previous count old, is so small that for an application like this is virtually impossible.

    Since Im no LINQ pro, i dont know whether LINQ actually gets app.DownLoadCount before adding one or just adds one through some SQL command, but in either case you shouldnt have to worry about that imho