I have a simple ASP.NET hosted WCF Service that has several methods that all have the same pattern when it comes to using the Entity Framework...
public void Operation1(string username)
{
using(MyEFContext context = new MyEFContext())
{
UserInfo info = (from ui in context.UserInfos
where ui.User.Equals(username)
select ui).FirstOrDefault<UserInfo >();
info.LastAccess = DateTime.Now;
// Operation specific code, such as getting information using the EF context
context.SaveChanges();
}
}
This is a cut down version to keep the example simple but even this simple version has the same error as my production set of code. The code starts by getting the users information using the Entity Framework, updates the users LastAccess field and then performs the operation specific code. The operation specific code just makes queries for information. At the end it calls SaveChanges so the LastAccess is saved back to the database. Now this all works perfectly fine until my client makes two calls in parallel.
The client makes two calls, each to a different operation but they both have the same pattern of code as seen above. Sometimes both calls complete with success. But other times one of them will produce as error and it could be any of the following three...
System.Data.EntityException: The underlying provider failed on Open. --->
System.InvalidOperationException: The connection was not closed. The connection^s current
state is connecting.
System.Data.EntityCommandExecutionException: An error occurred while executing the command
definition. See the inner exception for details. ---> System.InvalidOperationException:
ExecuteReader requires an open and available Connection. The connection^s current state is
closed.
System.InvalidOperationException: Invalid attempt to read when no data is present.
Clearly my understanding of EF and ASP.NET is flawed because I expected the two operations to work even in parallel. Do I need to put a lock around each method so they only occur one at a time? Surely not. Any ideas?