实体框架代码优先更改Identity UserRoles表

时间:2015-08-25 13:56:14

标签: entity-framework asp.net-mvc-5 code-first entity-framework-6.1

默认UserRolesUser映射了两个表RoleUserId 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

如何首先使用实体​​代码对PKUserId and RoleId and MyEntityId进行撰写,而无需手动触摸数据库?

1 个答案:

答案 0 :(得分:0)

UserId and RoleIdIdentityDbContext中通过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);
}