我已经使用ASP.net会员多年,我刚刚开始尝试ASP.net身份 . 他们刚刚发布了2.0版,它应该支持 int
主键 . 我已经定义了我的自定义标识类,以获得整数主键支持:
public class User : IdentityUser<int, UserLogin, UserRole, UserClaim>
{
}
public class UserLogin : IdentityUserLogin<int>
{
}
public class Role : IdentityRole<int, UserRole>
{
public string Description { get; set; } // Custom description field on roles
}
public class UserRole : IdentityUserRole<int>
{
}
public class UserClaim : IdentityUserClaim<int>
{
}
public class MyDbContext : IdentityDbContext<User, Role, int, UserLogin, UserRole, UserClaim>
{
public MyDbContext() : this("MyDB") { }
public MyDbContext(string connStringName) : base(connStringName)
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().ToTable("Users");
modelBuilder.Entity<Role>().ToTable("Roles");
modelBuilder.Entity<UserRole>().ToTable("UserRoles");
modelBuilder.Entity<UserLogin>().ToTable("UserLogins");
modelBuilder.Entity<UserClaim>().ToTable("UserClaims");
base.OnModelCreating(modelBuilder);
}
}
当我创建数据库迁移时,它会为每个标识表正确创建一个整数Id列,但是,它忽略了我在 OnModelCreating
方法中指定的自定义表名 . 相反,我得到的表名如 dbo.AspNetUsers
和 dbo.AspNetRoles
.
我也尝试将 [Table("TableName")]
添加到我的自定义标识类中,它没有任何效果 .
在查看ASP.net Identity 1.0的示例时,看起来他们使用基本Identity类重复了每个 modelBuilder.Entry<Type>().ToTable("TableName")
行:
modelBuilder.Entity<User>().ToTable("Users");
modelBuilder.Entity<IdentityUser<int, IdentityUserLogin<int>, IdentityUserRole<int>, IdentityUserClaim<int>>>().ToTable("Users");
modelBuilder.Entity<Role>().ToTable("Roles");
modelBuilder.Entity<IdentityRole<int, UserRole>>().ToTable("Roles");
modelBuilder.Entity<UserRole>().ToTable("UserRoles");
modelBuilder.Entity<IdentityUserRole<int>>().ToTable("UserRoles");
modelBuilder.Entity<UserLogin>().ToTable("UserLogins");
modelBuilder.Entity<IdentityUserLogin<int>>().ToTable("UserLogins");
modelBuilder.Entity<UserClaim>().ToTable("UserClaims");
modelBuilder.Entity<IdentityUserClaim<int>>().ToTable("UserClaims");
但是,我尝试了几种变体,我的迁移不会生成 . 我一直收到类似 The type Microsoft.AspNet.Identity.EntityFramework.IdentityUser'4[System.Int32,Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin'1[System.Int32],Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole'1[System.Int32],Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim'1[System.Int32]]' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive or generic, and does not inherit from EntityObject. 的错误
如何在ASP.net Identity 2.0中生成带有整数主键的自定义表名?
2 回答
Grrr ......所以在浪费了几个小时之后,我复制了我的规则并将它们粘贴在
base.OnModelCreating(modelBuilder);
线以下,一切正常 . 我没有意识到需要首先调用基本方法:(现在使用以下配置一切正常:
在IdentityModel.cs文件中,我将以下代码添加到
ApplicationDbContext
类中请注意,模型名称与接受的答案中列出的名称不同