我想映射這樣的東西:
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會將它們映射到自己的表中,我得到兩個一對一的關係,但這感覺不對。
建模這種情況的正確方法是什麼?
我認為下面的代碼有助於解決您的問題。有關詳細信息,請參閱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>();
}
}
使用EF Code First您可以這樣做
建議在實體類中包含外鍵屬性。例如,如果Foo實體包含FooPairId屬性,該屬性自動成為foreignkey屬性,因為它遵循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; }
}