Drill
Drill

Reputation: 169

DeadLock possibility in EntityFramework

I have this webmethod(called from android app)

    [WebMethod]
    public bool addVotes(string username,string password,int votes)
    {
        bool success= false;

        if (Membership.ValidateUser(username, password) == true)
        {
            DbContext context = new DbContext();
            AppUsers user = context.AppUsers.Where(x => x.Username.Equals(username)).FirstOrDefault();
            if (user != null)
            {
                user.Votat += votes;
                context.SaveChanges();
                success = true;
            }
        }
        return success;
    }

This web service will be called from 80 users(probably) in the same period of time(within two or three hours). I am afraid that there can occur a deadlock while reading or updating data in the database. Could you tell me weather there is a possibility of a deadlock and if there is such a possibility how can I prevent it with EF or sql or whatever.

Upvotes: 2

Views: 116

Answers (1)

Kristof
Kristof

Reputation: 3315

With this code : you can't

AppUsers user = context.AppUsers.Where(x => x.Username.Equals(username)).FirstOrDefault();

This line will wait for a readlock but eventually it will aquire one, so no deadlock possible.

context.SaveChanges();

This line will try and update your user table. It will wait for a writelock but it will eventually get one and then move on.
You can only get a deadlock while inserting / deleting / ... over multiple tables and usually it happens during a cursor iteration.
I have yet to bump in a situation where EF ends up in a deadlock, so i wouldn't worry about it too much.

Maybe you'll find this article usefull : http://blogs.msdn.com/b/diego/archive/2012/04/01/tips-to-avoid-deadlocks-in-entity-framework-applications.aspx

Upvotes: 1

Related Questions