EF核心:IEnumerable仅引用组合键的一部分

问题描述

好的,所以这可能是一个闻起来有点不好的设计的问题,但是现在我很好奇,知道是否有可能:D

我先做代码,但是要设法适应输出,以便可以从其他来源按1:1映射并填充表。

请考虑以下内容

public class A {
    [Key]
    public int Id { get; set; }
    
    public IEnumerable<B> Foo { get; set; }
}

public class B {
   [Key]
   public int Id { get; set; }

   [Key]
   public C Bar { get; set; }

   public string Description { get; set; }
}

public class C {
...
}

我想最终得到一个如下所示的数据库结构:

+-------+          +---------------+        +-----+
|   A   |          |       B       |        |  C  |
+-------+          +---------------+        +-----+
|Id   PK+--------->+Id           PK+------->+...  |
|B_Id   |          |C_Id         PK|        +-----+
+-------+          |Description    |
                   +---------------+

棘手/令人讨厌的部分是让 A.B_Id 仅引用B中主键的一部分,并且只包含可枚举的所有匹配项。 我尝试过的所有事情似乎都导致B中的新列引用了A,但我希望在可能的情况下将导航保持在另一个方向。

解决方法

好像是主键可以完成这项工作:https://docs.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key

通过向A添加一个包含所需ID B的字段

modelBuilder
    .Entity<A>(b =>
    {
        b.HasMany(x => x.Foo)
            .WithOne()
            .HasForeignKey(x => x.Id)
            .HasPrincipalKey(x => x.BId)
    });