简体   繁体   中英

"Context cannot be used while the model is being created" exception with ASP.NET Identity

Why is this happening when we make a call to the AccountApiController.Register() method?

  • what is trying to use the context?
  • what is trying to create the context?
  • how do we avoid this?
  • how do we debug this?

"Message":"An error has occurred.",

"ExceptionMessage":"The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method 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.",

"ExceptionType":"System.InvalidOperationException",

"StackTrace":"

at System.Web.Http.ApiController.d__1.MoveNext()

--- End of stack trace from previous location where exception was thrown

at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

at System.Runtime.CompilerServices.TaskAwaiter .HandleNonSuccessAndDebuggerNotification(Task > task)

at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__0.MoveNext()"

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;

This error can also occur in case of incorrect connectionString . Check if connectionString is valid (no typo etc.).

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?

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

我在 MySQL 的多层体系结构中使用 EF Code First 并且有相同的异常,并在 DBContext Class 构造中使用以下行:

Database.SetInitializer<EntitiesName>(null);

I agree with the main Answer by Shaun Luttin but also,

In my case: after the deployment i take this error and i found the reason is using the Hsts Preload after inserting SSL certificate. Uncommenting this lines solved the redirection, and it solved this error completely

 //app.UseHsts(options => options.MaxAge(days: 18 * 7).IncludeSubdomains().Preload());

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

TL&DR : If the goal is model seeding, and you are using the entity framework, i strongly suggest you take a look at the following link: https://docs.microsoft.com/en-us/ef/core/modeling/data-seeding

This link details how to directly SEED your data, during the migration itself. This is typically useful when you want to seed your data during the creation of the DATABASE instead of the start of your application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM