将Asp.Net Identity与自定义数据库一起使用

时间:2016-10-25 15:00:42

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

我将默认的AspNet标识表(AspNetUsers,AspNetLogin等)复制到我的数据库中,一切正常。然后我改变了他们的名字并使用以下方法创建了我自己的上下文:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<IdentityUser>()
            .ToTable("tblUsers", "dbo");

        modelBuilder.Entity<IdentityRole>()
            .ToTable("tblRoles", "dbo");

        modelBuilder.Entity<IdentityUserRole>()
            .ToTable("tblUserRoles", "dbo");

        modelBuilder.Entity<IdentityUserClaim>()
            .ToTable("tblUserClaims", "dbo");

        modelBuilder.Entity<IdentityUserLogin>()
            .ToTable("tblUserLogins", "dbo");
    }

但似乎应用程序仍然在寻找带有旧名称的表,因为我收到了错误:

enter image description here

请告诉我,我没有做过哪些必要的修改?

1 个答案:

答案 0 :(得分:0)

根据How can I change the table names when using Visual Studio 2013 ASP.NET Identity?,这应该有效:

protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<IdentityUser>().ToTable("MyUsers").Property(p => p.Id).HasColumnName("UserId");
    modelBuilder.Entity<ApplicationUser>().ToTable("MyUsers").Property(p => p.Id).HasColumnName("UserId");
    modelBuilder.Entity<IdentityUserRole>().ToTable("MyUserRoles");
    modelBuilder.Entity<IdentityUserLogin>().ToTable("MyUserLogins");
    modelBuilder.Entity<IdentityUserClaim>().ToTable("MyUserClaims");
    modelBuilder.Entity<IdentityRole>().ToTable("MyRoles");
}

还要确保你没有陷入ASP.NET身份使用其默认aspnetdb.mdf数据库的陷阱,并检查你的web.config是这样的:

<connectionStrings>
   <remove name="LocalSqlServer" />
   <add connectionString="yourdatabase" name="LocalSqlServer" providerName="System.Data.SqlClient" />
</connectionStrings>