EF不创建AspNet标识表

时间:2014-09-16 18:09:18

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

我有一个简单的aspnet Identity模式但我无法在我的数据库中创建Identity表。 下面是MVC网站用于标识的主要类:

 public class ApplicationUser : IdentityUser
{
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        if (modelBuilder == null)
        {
            throw new ArgumentNullException("modelBuilder");
        }

        modelBuilder.Entity<IdentityUser>().ToTable("AspNetUsers");
        EntityTypeConfiguration<ApplicationUser> table =
            modelBuilder.Entity<ApplicationUser>().ToTable("AspNetUsers");

        table.Property((ApplicationUser u) => u.UserName).IsRequired();

        modelBuilder.Entity<ApplicationUser>().HasMany<IdentityUserRole>((ApplicationUser u) => u.Roles);
        modelBuilder.Entity<IdentityUserRole>().HasKey((IdentityUserRole r) =>
            new { UserId = r.UserId, RoleId = r.RoleId }).ToTable("AspNetUserRoles");

        EntityTypeConfiguration<IdentityUserLogin> entityTypeConfiguration =
            modelBuilder.Entity<IdentityUserLogin>().HasKey((IdentityUserLogin l) =>
                new
                {
                    UserId = l.UserId,
                    LoginProvider = l.LoginProvider,
                    ProviderKey
                        = l.ProviderKey
                }).ToTable("AspNetUserLogins");

        entityTypeConfiguration.HasRequired<IdentityUser>((IdentityUserLogin u) => u.User);
        EntityTypeConfiguration<IdentityUserClaim> table1 =
            modelBuilder.Entity<IdentityUserClaim>().ToTable("AspNetUserClaims");

        table1.HasRequired<IdentityUser>((IdentityUserClaim u) => u.User);

        modelBuilder.Entity<IdentityRole>().ToTable("AspNetRoles");

        EntityTypeConfiguration<IdentityRole> entityTypeConfiguration1 =
            modelBuilder.Entity<IdentityRole>().ToTable("AspNetRoles");

        entityTypeConfiguration1.Property((IdentityRole r) => r.Name).IsRequired();
    }
}

当我尝试登录时,OnModelCreating方法会执行,但是当我进入数据库时​​,表格没有被创建,我得到错误&#34;无效的列名称AspNetUsers&#34;。 这有什么不对吗?

1 个答案:

答案 0 :(得分:5)

加入Global.Asax add

Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ApplicationDbContext>());

这将在每次模型更改时删除并重新创建数据库。

详细了解Entity Framework Database Initialization Strategies