0

По умолчанию UserRoles сопоставил две таблицы User и Role по UserId and RoleId и имеет составной ключ на вышеуказанных столбцах.Составной код с кодовым преобразованием Entity Framework в таблицах Identity UserRoles

Я настроен, что, добавив еще две объектных отношений:

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.

Как я могу сделать composete PK: UserId and RoleId and MyEntityId с кодом сущности сначала без прикосновения к базе данных вручную?

ответ

0

UserId and RoleId сконфигурирован как ПК с помощью свободного API в IdentityDbContext. Вам необходимо перезаписать IdentityDbContext модельный конструктор, чтобы добавить свой собственный ПК. Поэтому переопределите метод OnModelCreating вашего 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); 
}