EF Core - 用外键连接两个表

EF Core - Connect two tables with foreign key

我有两个 EF Core 实体,我想通过不遵循 id-name-convention 的字符串键连接。还有一个像这样的简单 DbContext:

public DbSet<Entity1> Table1 { get; set; }
public DbSet<Entity2> Table2 { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Entity1>()
                .HasOne(s => s.Entity2) 
                .WithOne()
                .HasForeignKey<Entity1>(s => s.Name); 
}

public class Entity1
{
    public String Name{ get; set; }
    public Entity2 Entity2 { get; set; }
}

public class Entity2
{
    [Key]
    public String Nummer { get; set; }
}

它不会抛出任何错误 - 但查询数据时,“Entity2”属性 始终为空 - 即使 Table2 中有一个数据集,其中“Nummer”等于“Name”值实体 1.

我也尝试了没有 OnModelCreating-Code 的 ForeignKey-Attribute - 但结果相同。

我认为,我对EF core中的外键概念完全误解了。

有什么想法或提示吗?

问题可能出在查询过程中。你如何查询数据。默认情况下,EFCore 不会进行连接查询,除非您通过 Include() 明确指定它。例如,

var entity1 = db.Table1
    .Where(x=>x.Name == "test")
    .Include(x=>x.Entity2)     <--- watch this
    .First();

Include(x=>x.Entity2)指定两个表之间存在连接查询,返回的Entity1对象包含Entity2.

的数据