我想映射这样的东西:
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.
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/