简体   繁体   中英

Entity Framework Code First : Two DbContext and one database initializers

I have two DbContext in my Project : ApplicationDbContext for ApplicationUser model (inherited from ASP.NET Identity IdentityUser class) and EFDbContext for all other models.

They use one database.

I created two database initializers for each of context:

 public class ApplicationDbInitializer : 
     DropCreateDatabaseIfModelChanges<ApplicationDbContext>
 {
     protected override void Seed(ApplicationDbContext context)
     {
        // add Admin role and user

        ... code here
        //
        base.Seed(context);
     }
}

And

 public class EFDbInitializer : DropCreateDatabaseAlways<EFDbContext>
 {
        protected override void Seed(EFDbContext context)
        {
        }
 }

The problem:

I get such error in App

An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.dll but was not handled in user code

Additional information: Cannot drop database "DatabaseName" because it is currently in use.

I think it tries re-create database using one context initializer but database is in using by another context.

How to deal with such error?

Most of the times, using multiple db-contexts for the same database is considered as a bad practice. But if you really need this, I am quoting the great answer by Ladislav Mrnka from here :

The problem is when you want to use code first to create your database - only single context in your application can do that. The trick for this is usually one additional context containing all your entities which is used only for database creation. Your real application contexts containing only subsets of your entities must have database initializer set to null.

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