在 EF Core 2.1.1 中配置交集 table

Configuring intersection table in EF Core 2.1.1

我有一个非常简单的需求,但我不知道如何先在代码中使用 EF core 2.1.1 来实现它。

我有一个 table Right 和一个 table Role:

Role
public int RoleId { get; set; }
public string Name { get; set; }

Right  
public int RightId { get; set; }  
public string Name { get; set; }  

通常,在标准数据库中,我会简单地创建一个交集 table Named:

RoleRights(RoleId int, RightId int)  

但似乎在 ef core 2.1.1 中,您改为添加导航属性。

Role
public int RoleId { get; set; }
public string Name { get; set; }
public IEnumerable<Right> Rights { get; set; } 

Right
public int RightId { get; set; }  
public string Name { get; set; } 
public IEnumerable<Role> Roles { get; set; } 

一个Role可以包含任意数量的Right,一个Right可以包含任意数量的Role

通过做:

modelBuilder.Entity<Role>().HasMany(r => r.Rights);
modelBuilder.Entity<Right>().HasMany(r => r.Roles);

它压平了我的 Role table 并添加了一个 RightId 而不是形成一个交集 table。 Right table 也一样。它添加了一个 RoleId.

Migration 脚本中:

migrationBuilder.AddColumn<int>(
    name: "RightId",
    table: "Roles",
    nullable: true);

migrationBuilder.AddColumn<int>(
    name: "RoleId",
    table: "Rights",
    nullable: true);
    migrationBuilder.AddForeignKey(
        name: "FK_Rights_Roles_RoleId",
        table: "Rights",
        column: "RoleId",
        principalTable: "Roles",
        principalColumn: "Id",
        onDelete: ReferentialAction.Restrict);

    migrationBuilder.AddForeignKey(
        name: "FK_Roles_Rights_RightId",
        table: "Roles",
        column: "RightId",
        principalTable: "Rights",
        principalColumn: "Id",
        onDelete: ReferentialAction.Restrict);

如何配置我的模型,使其具有交集 table?在这种情况下,它生成了错误的模式。我无法在 Role 中插入和清空 RoleRight。想想看,反正我应该永远不会那样做,但我觉得很奇怪。

感谢您的宝贵时间!

如果有任何不清楚的地方,请告诉我哪些地方需要更详细,我会澄清的!

所以我遵循了一些过时的东西。解决方案是显式地进行连接 table.

   public class RoleRight : IEntity
   {
      public int RoleId { get; set; }
      public Role Role { get; set; }

      public int RightId { get; set; }
      public Right Right { get; set; }
   }

权利和角色看起来像这样。

   public class Right : IEntity
   {
      public int Id { get; set; }
      public string Name { get; set; }
      public virtual List<RoleRight> RoleRights { get; set; }
   }

在 OnModelCreating 上使用此配置

 modelBuilder.Entity<RoleRight>().HasKey(rr=> new { rr.RightId, rr.RoleId });
 modelBuilder.Entity<RoleRight>().HasOne(rr => rr.Right)
                                 .WithMany(r => r.RoleRights)
                                 .HasForeignKey(rr => rr.RightId);

 modelBuilder.Entity<RoleRight>().HasOne(rr => rr.Role)
                                 .WithMany(r => r.RoleRights)
                                 .HasForeignKey(rr => rr.RoleId);

这基本上是我之前在评论中提供的 link 的最后一部分。 我不知道我第一次阅读该页面时怎么会错过它!