【问题标题】:EF Core - Connect two tables with foreign keyEF Core - 使用外键连接两个表
【发布时间】:2020-08-25 16:21:38
【问题描述】:

我想通过不遵循 id-name-convention 的字符串键连接两个 EF Core 实体。还有一个像这样的简单 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”等于 Entity1 的“Name”值。

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

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

有什么想法或提示吗?

【问题讨论】:

    标签: c# entity-framework-core foreign-keys


    【解决方案1】:

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

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

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

    【讨论】:

    • 这就是重点 :-) 我认为 EF Core 会为我做这件事 ;-) 非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多