默认UserRoles
按User
映射了两个表Role
和UserId and RoleId
,并在上面的列中包含复合键。
我通过添加两个实体关系来定制它:
public class CustomUserRole : IdentityUserRole<int>
{
[Key]
public int MyEntityId { get; set; }
public virtual MyEntity MyEntity { get; set; }
}
我已经有了这个迁移脚本:
public override void Up()
{
CreateTable(
"dbo.MyEntity",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
AddColumn("dbo.UserRoles", "MyEntityId", c => c.Int(nullable: false));
CreateIndex("dbo.UserRoles", "MyEntityId");
AddForeignKey("dbo.UserRoles", "MyEntityId", "dbo.MyEntity", "Id", cascadeDelete: true);
}
更新数据库后,UserRole
表中又有一个名为MyEntityId
的列,但它被添加为FK
。我原本希望有一个复合主键UserId and RoleId and MyEntityId
。
如何首先使用实体代码对PK
:UserId and RoleId and MyEntityId
进行撰写,而无需手动触摸数据库?
答案 0 :(得分:0)
UserId and RoleId
在IdentityDbContext
中通过fluent API配置为PK。您需要覆盖IdentityDbContext
的模型构建器以添加您自己的PK。因此,请覆盖OnModelCreating
。{/ p>的DbContext
方法
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
if (modelBuilder == null)
{
throw new ArgumentNullException("modelBuilder");
}
var user = modelBuilder.Entity<ApplicationUser>()
.ToTable("AspNetUsers");
user.HasMany(u => u.Roles).WithRequired().HasForeignKey(ur => ur.UserId);
user.HasMany(u => u.Claims).WithRequired().HasForeignKey(uc => uc.UserId);
user.HasMany(u => u.Logins).WithRequired().HasForeignKey(ul => ul.UserId);
user.Property(u => u.UserName)
.IsRequired()
.HasMaxLength(256)
.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("UserNameIndex") { IsUnique = true }));
user.Property(u => u.Email).HasMaxLength(256);
// We add our PK there other configurations are Identity's default.
modelBuilder.Entity<CustomUserRole>()
.HasKey(r => new { r.UserId, r.RoleId, r.MyEntityId })
.ToTable("AspNetUserRoles");
modelBuilder.Entity<IdentityUserLogin>()
.HasKey(l => new { l.LoginProvider, l.ProviderKey, l.UserId })
.ToTable("AspNetUserLogins");
modelBuilder.Entity<IdentityUserClaim>()
.ToTable("AspNetUserClaims");
var role = modelBuilder.Entity<MyIdentityRole>()
.ToTable("AspNetRoles");
role.Property(r => r.Name)
.IsRequired()
.HasMaxLength(256)
.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("RoleNameIndex") { IsUnique = true }));
role.HasMany(r => r.Users).WithRequired().HasForeignKey(ur => ur.RoleId);
}