在EF Core 2.1.1

时间:2018-07-06 19:41:34

标签: entity-framework-core-2.1 ef-core-2.1

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

我有一个表Right和一个表Role

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

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

通常,在标准数据库中,我只需制作一个交集表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表并添加了RightId而不是制作一个交集表。 Right表也是如此。它会添加一个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);

如何配置模型以具有交集表?在这种情况下,它将生成错误的架构。我无法在没有Role的情况下插入RightRole并清空。考虑到这一点,我可能永远也不要这样做,但是对我来说感觉很奇怪。

感谢您的时间!

如果不清楚,请告诉我什么需要更详细的信息,我会澄清!

1 个答案:

答案 0 :(得分:0)

所以我遵循了一些过时的方法。解决方案是显式创建联接表。

   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);

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

相关问题