【问题标题】:Entity Framework Core 2.0 many-to-many relationships same table [duplicate]Entity Framework Core 2.0多对多关系同一张表[重复]
【发布时间】:2018-09-25 03:14:57
【问题描述】:

我正在使用 Entity Framework Core 2.0 来映射现有 DB,该 DB 有两个表:TeamsSupportTeam

团队字段: ID、名称

TeamSupport:TeamID(团队表上的外键)、SupportTeamID(团队表上的外键)

我尝试将它们映射如下:

 public class Team
 {
     public int Id { get; set; }
     public string name { get; set; }

     public List<TeamSupport> SupportTeams { get; set; }

 }

 public class TeamSupport
 {
     public int TeamId { get; set; }
     public virtual Team Team { get; set; }

     public int SupportTeamId { get; set; } // In lack of better name.
     public virtual Team SupportTeam { get; set; }
 }

但是当我运行“add-migration”时出现以下错误:

无法确定导航所代表的关系 “列表”类型的属性“Team.SupportTeams”。任何一个 手动配置关系,或使用 '[NotMapped]' 属性或使用 'EntityTypeBuilder.Ignore' 'OnModelCreating'。

【问题讨论】:

    标签: c# entity-framework-core


    【解决方案1】:

    TeamSupport 实体有 两个 reference 导航属性到Team(定义了TeamSupportTeam 之间的两个多对一关系) ,但 Team 实体只有 一个 collection 导航属性,因此 EF 不知道如何映射它(到 Team.TeamTeam.SupportTeam)并抛出有问题的例外。

    在这种情况下,您必须明确地解析映射。通常使用[InverseProperty] 数据注释就足够了,但是对同一个表的多次引用总是会导致多个级联路径问题,这需要为一个或多个关系关闭删除级联。而后者只能通过fluent配置来完成,所以最好也用fluent配置来做整个映射。

    您的模型现在所需的最低配置是:

    modelBuilder.Entity<TeamSupport>()
        .HasOne(e => e.Team)
        .WithMany(e => e.SupportTeams);
    
    modelBuilder.Entity<TeamSupport>()
        .HasOne(e => e.SupportTeam)
        .WithMany()
        .OnDelete(DeleteBehavior.Restrict);
    

    注意,由于没有对应的集合导航属性,第二个关系配置使用无参数的WithMany 重载来表示。如果您决定将此类集合添加到模型中

    public class Team
    {
        public int Id { get; set; }
        public string name { get; set; }
    
        public List<TeamSupport> SupportTeams { get; set; }
        public List<TeamSupport> SupportOfTeams { get; set; } // <--
    }
    

    别忘了在对应的映射中注明

    .WithMany(e => e.SupportOfTeams)
    

    否则 EF 将创建第三个关系。

    有关详细信息,请参阅 EF Core 文档的Relationhips 部分。

    【讨论】:

    • 在这种情况下,SupportTeams 类型是 List。我怎样才能将 SupportTeams 作为 List. 返回
    • 如果您的意思是在模型级别,您目前不能像答案中的文档链接中的Many-to-many 小节所述:“没有实体类的多对多关系表示连接表尚不支持。”但您始终可以使用 LINQ SelectTeamSupport 列表中提取SupportTeam 属性。
    猜你喜欢
    • 2018-08-06
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多