ASP.NET Identity 2初始化程序删除了我的所有表

时间:2018-03-17 08:52:46

标签: c# asp.net-mvc entity-framework asp.net-identity

我使用的是asp.net身份,2.21版本。只要在Global.asax中触发了AppDbInitializer,LibraryContext中的所有表都将被删除。所以我得到SqlException:无效的对象名称' dbo.Books'错误。我想,问题出在我的初始化者身上,但不知道在哪里。所有表都使用相同的" DefaultConnection"字符串。

我的LibraryContext和初始化程序:

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);
    }
}

身份初始化程序:

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 = "somemail@mail.ru", UserName = "somemail@mail.ru" };
        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);
    }
}

1 个答案:

答案 0 :(得分:0)

我在这里为CreateDatabaseIfNotExists更改了DropCreateDatabaseAlways:。

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

现在它正在发挥作用!)