与实体框架核心上的同一个表的两个一对一关系

时间:2016-11-22 12:26:26

标签: 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导航属性所代表的关系。

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

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

2 个答案:

答案 0 :(得分:1)

我认为下面的代码有助于解决您的问题。  有关详细信息,请参阅Eftutorials

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

public class FooPair
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public int Id { get; set; }   
   public virtual ICollection<Foo> Foos { get; set; }

   public Foo()
    {
        Foos = new List<Foo>();
    }
}

答案 1 :(得分:1)

使用EF Code First你可以这样做

  

建议在实体类中包含外键属性。   例如,如果Foo实体包含FooPairId属性   自动成为foreignkey属性,因为它遵循   外键的约定&lt;输入名称&gt; 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; }
}