c# - Entity Framework Core 上同一个表的两个一对一关系

标签 c# entity-framework entity-framework-core

我想映射这样的东西:

public class FooPair
{
    public int Id { get; set; }
    public Foo Foo1 { get; set; }
    public Foo Foo2 { get; set; }
}

public class Foo
{
    public int Id { get; set; }
    public FooPair Parent { get; set; }
}

还有我的 DbContext:

public class FooContext : DbContext
{
    public DbSet<Foo> Foos { get; set; }
    public DbSet<FooPair> Pairs { get; set; }
}

EF 提示它无法确定 Parent 导航属性表示的关系。

我能想到的唯一解决方案是从 Foo 创建两个新的继承类,然后 EF 将它们映射到它们自己的表,我得到两个 1 对 1 的关系,但是这个感觉不对。

对这种情况建模的正确方法是什么?

最佳答案

使用 EF Code First,您可以这样做

It is recommended to include foreign key property in an entity class. For example, if Foo entity includes FooPairId property which automatically becomes foreignkey property because it follows the convention for foreignkey < Type Name >Id.

Here you find tutorial

public class FooPair
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public Foo Foo1 { get; set; }
    public Foo Foo2 { get; set; }
    public virtual Foo Foo { get; set; }
}

public class Foo
{
    public Foo()
    {
        FooPairs = new List<FooPair>();
    }
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public int FooPairId { get; set; }
    [ForeignKey("FooPairId")]
    public ICollection<FooPair> FooPairs { get; set; }
}

关于c# - Entity Framework Core 上同一个表的两个一对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40741837/

相关文章:

c# - 上传时检查文件大小的推荐方法

c# - 如何在DXChart中显示数据表

entity-framework - 从集合域驱动设计中删除对象

entity-framework - 数据库优先验证

c# - 模型更改后更新数据库 - Entity Framework 7

c# - 升级到 ASP.NET Core 2.0 后无法创建迁移

C#、WinForms : Why isn't OnPaintBackground called when I call Refresh()?

C#从套接字接收数据并将其放入字符串中?

c# - 没有使用()范围的DAL方法中的 Entity Framework 新的dbContext

entity-framework-core - 使用 Microsoft.EntityFrameworkCore.InMemory 测试并发 token