Search code examples
c#asp.net-mvcentity-frameworkasp.net-identity

ASP.NET Identity 2 initializer drop all my tables


I'm using asp.net identity, 2.21 version. As soon as my AppDbInitializer is triggered in Global.asax, all tables in LibraryContext are deleted. So I get SqlException: Invalid object name 'dbo.Books' error. I think, the problem is in my initializers, but don't know where. All tables use the same "DefaultConnection" string.

My LibraryContext and initializer:

public class Library : DbContext
{
    public Library(string connectionString)
       : base(connectionString)
    {
        Database.SetInitializer(new LibraryDbInitializer());
    }
    public DbSet<Book> Books { get; set; }        
}

public class LibraryDbInitializer : DropCreateDatabaseAlways<Library>
{
    protected override void Seed(Library db)
    {
        //shortened for brevity
        base.Seed(db);
    }
}

Identity initializer:

public class AppDbInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
{
    protected override void Seed(ApplicationDbContext context)
    {
        var userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(context));

        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

        var role1 = new IdentityRole { Name = "admin" };
        var role2 = new IdentityRole { Name = "user" };

        roleManager.Create(role1);
        roleManager.Create(role2);

        var admin = new ApplicationUser { Email = "[email protected]", UserName = "[email protected]" };
        string password = "ad46D_ewr3";
        var result = userManager.Create(admin, password);

        if (result.Succeeded)
        {
            userManager.AddToRole(admin.Id, role1.Name);
            userManager.AddToRole(admin.Id, role2.Name);
        }

        base.Seed(context);
    }
}

Solution

  • I've changed DropCreateDatabaseAlways for CreateDatabaseIfNotExists here:.

    public class AppDbInitializer : CreateDatabaseIfNotExists<ApplicationDbContext>// DropCreateDatabaseAlways was
    

    And now it's working!)