Why is this happening when we make a call to the AccountApiController.Register() method?
The problem was that we were NOT using the factory pattern that MS recommends.
You can use Factory implementation to get an instance of UserManager from the OWIN context. ... This is a recommended way of getting an instance of UserManager per request for the application.
As a result, "the same context instance is accessed by multiple threads concurrently," because several requests and thus threads shared a DbContext.
This following is correct. It creates a new instance of MyDbContext for each call to the UserManagerFactory function.
UserManagerFactory
= () => new UserManager<IdentityUser>(new UserStore<IdentityUser>(new MyDbContext()));
The following is incorrect. It look similar but does not create a new instance for each call to UserManagerFactory. It is what we were using, ergo our site broke.
var userStore = new UserStore<IdentityUser>(new MyDbContext());
var userManager = new UserManager<IdentityUser>(userStore);
UserManagerFactory = () => userManager;
If you are getting records from Table/View make sure you have sufficient access on the DB objects.
I had the same problem and i resolved it by executing
sp_change_users_login [ @Action = ] 'action' [ , [ @UserNamePattern = ] 'user' ] [ , [ @LoginName = ] 'login' ] [ , [ @Password = ] 'password' ] [;]
sp_change_users_login 'update_one' 'dbuser' 'dblogin'
Find more snippet and details
Do you override the OnModelCreating method? If so, can you share it or the whole context class?
If not, you should pay attention to the following in the error message
or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.
If that doesn't help, do you use an unchanged Web API project which is created by Visual Studio?
In my case, I got this message when I run multi-threading tasks and I follow the solution form EL Vany. His solution is quite good. Now I can run 100x threads at the same time without any exception.
http://elvanydev.com/EF-DbContextFactory/#comments-1
This error can also occur in case of incorrect connectionString
. Check if connectionString
is valid (no typo etc.).
I'm using EF Code First in a multi-layered architecture with MySQL and had the same exception and using the following line inside the DBContext Class constructure works:
Database.SetInitializer<EntitiesName>(null);