views:

194

answers:

1

Hi I am using the ADO.NET entity framework for the first time and the staticcode analysis is suggesting I change the following method to a static one as below.

My question is simple, is this thread safe?

public static void InsertUserDetails(UserAccount userAccount)
        {
            using (KnowledgeShareEntities entities = new KnowledgeShareEntities())
            {
                Users user = new Users();
                user.usr_firstname = userAccount.FirstName;
                user.usr_surname = userAccount.LastName;
                user.usr_email = userAccount.Contact.Email;
                user.usr_logon_name = userAccount.SAMUserAccountName.ToUpper();
                user.usr_last_login_datetime = DateTime.Now;
                entities.AddToUsers(user);
                entities.SaveChanges();
            }
        }
+1  A: 

As you are using only local variables the method is thread safe. There are no static variables involved so everything will be on the thread local stack and no race conditions could occur.

Darin Dimitrov
I agree that it is thread safe because it only uses local variables, but that is probably the only reason the static code analysis suggests it should be a static method, as static data access is usually not a great idea. Any code that uses this static method to insert a user has a static dependency that is difficult to mock during unit tests, meaning unit testing code that calls this static method means the test has to go against a real database.Perhaps the original poster change the title to ask about thread safety.
flipdoubt
@flipdoubt you are absolutely right pointing out that static methods are difficult to test and should not be used in this case but this is a little out of topic as the OP just asked about thread safety.
Darin Dimitrov