nvcnvn
nvcnvn

Reputation: 5175

Can EF Code First have two more DBContext in one App?

I have an ASP.NET MVC App, which use EF code First, for some reason I need to use 2 differents DBContext for my app like the example here:

namespace ESN.Models
{
    public class CoreA
    {
        //..........
    }

    public class CoreB
    {
        //..........
    }

    public class CoreDbContext : DbContext
    {
        public DbSet<CoreA> CoreA { get; set; }
        public DbSet<CoreB> CoreB { get; set; }
    }

    public class StuffA
    {
        //..........
    }

    public class StuffB
    {
        //..........
    }

    public class StuffDbContext : DbContext
    {
        public DbSet<StuffA> StuffA { get; set; }
        public DbSet<StuffB> StuffB { get; set; }
    }
}

And for the convenient developing I add some code that drop and re-create the database if model has change:

    Database.SetInitializer<CoreDbContext>(new DropCreateDatabaseIfModelChanges<CoreDbContext>());
    Database.SetInitializer<StuffDbContext>(new DropCreateDatabaseIfModelChanges<StuffDbContext>());

But the issue is they just Create new table for the DbContent that I need to use first, the Core table exist but none of the Stuff!

Thanks for your help!

Upvotes: 1

Views: 969

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

If you want to use two DbContext types and database initializers each context must use its own database. If you use the same database for both context types you cannot use database initializers and you must maintain the database schema changes manually (you must manually or through some SQL script create database and all necessary tables prior to using the application).

Upvotes: 1

Related Questions