Strategy for thread-safe database access
===

Say I have the following code that inserts users into MS Dynamics in a MVC Application:

    public bool CreateContact(string email)
    {
        if (crm.contacts.Count(x => x.Email == email) > 0)
             return false; //Email already exist in the Crm. Skip
    
        var contact = new contact {Email = email};
        crm.AddTocontacts(contact);
        crm.SaveChanges();

        return true;
    }

It works great for stopping users from registering with the same Email address, until recently when we are having MAJOR performance issues with Dynamics. 

Apparently, users are getting a huge delay and often triple clicks the button that fires this piece of code. 

Problem is, .Count() is firing at the same time in different Http Requests before .SaveChanges() finished in the first Request. As a result, we are seeing contacts with the same Email address.

While I already added a fix from the client-side, I would like to see if this can be done on the server side as well.

What would be a good strategy to make this thread-safe?

Thank you,

Chi
