Geethanga
Geethanga

Reputation: 1846

Automatically updating database with multiple DbContexts

I'm using EF6 in ASP.NET 5 project. Where I'm using ASP.NET Identity as the authentication mechanism. As anyone would do, I have modeled my domain objects in a separate dll project and for data access logic I have a separate project. This data project contains EF migrations, DbContext for domain models, repositories and Unit of work.

And I have a service layer which is contacted by ASP.NET controllers and this service layer will communicate with data layer and do required operations.

In the main ASP.NET web project I have the default DbContext which is related to Identity and it's migrations.

Having two DbContexts somehow prevents me from updating database automatically. If I had only one DbContext after I create migrations for model changes, it will automatically run on the first time I try to access the website. This doesn't happen anymore, always I have to run the "update-database" command manually.

One solution I have right now is to add a reference to "Microsoft.AspNet.Identity.EntityFramework" in my data project and use Identity context contain my domain tables. But adding an ASP.NET reference in my data project is something I don't want to do unless I have no other options. Because data layer is not even communicating directly with web layer.

Even though this video by Scott Allen discuss about this issue, a solution is not proposed.

Upvotes: 2

Views: 865

Answers (2)

Mohsen Esmailpour
Mohsen Esmailpour

Reputation: 11554

You can run migration inside each DbContext constructor separately.

public class DataContext: DbContext 
{
    static DaraContext() 
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataContext, Configuration>());
    }
}


public class ApplicationDbContext : IndetityDbContext 
{
    static ApplicationDbContext() 
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>());
    }
}

Upvotes: 1

cincura.net
cincura.net

Reputation: 4150

You can kick in migrations explicitly by using database initializer and using MigrateDatabaseToLatestVersion. This initializer allows you explicitly state the context and configuration you want to use. Something like:

SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Configuration>()); 

You can also call all the logic manually, effectively doing the same as Update-Database cmdlet, when you want during app start. Look at DbMigrator class.

Upvotes: 1

Related Questions