Search code examples
c#entity-frameworkasp.net-mvc-5code-firstentity-framework-migrations

Enabling auto migration at an Identity Context


I'm using .NET MVC 5 to create an application. I'm using the code first approach. I have a separated assembly to put my database classes, and have separated my context in different migrations folders. So far I have 2 contexts, and one is the IdentityDb that inherits from IdentityDbContext. So far, so good. But when I try to enable auto migrations (because I still don't have an production version and an auto migration will not hurt), something bad happens at IdentityDb. This is how I enabled the Auto Migration:

public class IdentityDb : IdentityDbContext<ApplicationUser>
{
    public IdentityDb() : base("DefaultConnection")
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<IdentityDb, Configuration>("DefaultConnection"));
    }
}

Of Course I have the Configuration class, with the seed method, and AutomaticMigrationsEnabled property set to true. Everything seems fine, but when I try to do something that needs the Identity context (such as login), I get this error message:

The ConnectionString property has not been initialized

The line it says there is the error is at:

public IdentityDb() : base("DefaultConnection")

But it is. I assume that when I pass it as "DefaultConnection" at the base constructor and when instantiating the MigrateDatabaseToLatestVersion, the connection string is set.

Finally, I want to say that this only happen at IdentityDb context. I have auto migrations enabled in my other context, CampaignsDb, exactly the same way, and it works perfectly. Does anyone have an idea about what's happening with the IdentityDb? Is the problem because this class inherits the IdentityDbContext, and the auto migrations should be enabled with a different approach?


Solution

  • remove the "DefaultConnection" from MigrateDatabaseToLatestVersion. You already have your configuration type passed in, which in turn should be using your DBContext. So it would be like this:

    Database.SetInitializer(new MigrateDatabaseToLatestVersion<IdentityDb, Configuration>());