Rovdjuret
Rovdjuret

Reputation: 1528

IdentityDbContext not creating tables with DropCreateDatabaseAlways

I'm working on this WebApi project where I'm using latest version of authentication. My two Context setups looks like this, one is autogenerated for authentication and one is my own dbcontext for other tables:

ApplicationDbContext for Authentication tables

public class IdentityContext : IdentityDbContext<ApplicationUser>
{
    public IdentityContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {

    }

    public static IdentityContext Create()
    {
        return new IdentityContext();
    }
}

MyDbContext

public class Context : DbContext
{
    public Context()
        : base("name=DefaultConnection")
    {
        this.Configuration.LazyLoadingEnabled = true;
        this.Configuration.ProxyCreationEnabled = true;
        Database.SetInitializer(new DropCreateInitializer());
        this.Database.CreateIfNotExists();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
       //FluentApi
    }
}

DropCreateInitializer

public class DropCreateInitializer : DropCreateDatabaseAlways<Context>
{
    protected override void Seed(Context context)
    {
        // Seeding works nice here
    }
}

My problem is as soon as I got this working with DropCreateDatabaseAlways and seed, it doesn't recreate my tables for the authentication. I just can't figure out why?

Please help!

Kind regards, Haris

Upvotes: 0

Views: 2307

Answers (1)

Christoffer Mansfield
Christoffer Mansfield

Reputation: 803

You're only creating and setting an initializer for the Context class.

If you want your IdentityContext class to also drop and recreate always, you need to implement an additional initializer for that class:

public class IdentityDropCreateInitializer : 
    DropCreateDatabaseAlways<IdentityContext>
{
    protected override void Seed(Context context)
    {
        //Seed identity tables here
    }
}

And then assign that to the IdentityContext like so:

public IdentityContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
        Database.SetInitializer(new IdentityDropCreateInitializer());
    }

Upvotes: 1

Related Questions