我有一个ASP MVC 5应用程序,但模型构建器正在为IdentityUserRole,IdentityUserClaim和IdentityUserLogin表创建重复的外键。
下面生成的迁移表中的
CreateTable(
"dbo.UserRole",
c => new
{
RoleId = c.String(nullable: false, maxLength: 128),
UserId = c.String(nullable: false, maxLength: 128),
IdentityRole_Id = c.String(maxLength: 128),
ApplicationUser_Id = c.String(maxLength: 128),
})
.PrimaryKey(t => new { t.RoleId, t.UserId })
.ForeignKey("dbo.Role", t => t.IdentityRole_Id)
.ForeignKey("dbo.User", t => t.ApplicationUser_Id)
.Index(t => t.IdentityRole_Id)
.Index(t => t.ApplicationUser_Id);
在我流利的api中,我的定义如下:
public IdentityUserRoleConfiguration()
{
HasKey(x => new { x.RoleId, x.UserId });
ToTable("UserRole");
}
我的模型构建者类:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
// Add some DBSets
public ApplicationDbContext()
: base("ApplicationDbContext", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
// base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new IdentityUserRoleConfiguration());
modelBuilder.Configurations.Add(new IdentityUserLoginConfiguration());
modelBuilder.Configurations.Add(new IdentityRoleConfiguration());
modelBuilder.Configurations.Add(new IdentityUserClaimConfiguration());
modelBuilder.Configurations.Add(new ApplicationUserConfiguration());
}
}
我已经注释掉了base.OnModelCreating(modelBuilder);
语句,因为它在我运行迁移时会抛出以下错误:
A configuration for type 'Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole' has already been added. To reference the existing configuration use the Entity<T>() or ComplexType<T>() methods.
答案 0 :(得分:0)
配置可以如下实现,
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityRole>().ToTable("Roles");
modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles");
modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims");
modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLoginProviders");
modelBuilder.Configurations.Add(new UserConfiguration());
}
由于Microsoft.AspNet.Identity.EntityFramework
中的大多数 IdentityRole,IdentityUserRole,IdentityUserClaim,IdentityUserLogin 模型已经实现了流畅配置,因此它只允许覆盖ApplicationUser。因此,实现他的唯一方法就是Entity<T>()