![](/img/trans.png)
[英]How can I use Fluent API in Entity Framework 6 to Map a List of One To Many objects without a foreign key property?
[英]Entity Framework One to many fluent Api - foreign key
我想在兩個實體之間建立聯系。
我有Entity_1和Entity_2,它們之間的關系是一對多(一個Entity_1可以有多個Entity_2)。
所以我有我的實體:實體
class Entity_1
{
public int Id { get; set; }
public int Entity_2Id{ get; set; }
public virtual Entity_2 Entity_2{ get; set; }
}
class Entity_2
{
public int Id { get; set; }
public int Entity_2Id{ get; set; }
public virtual ICollection<Entity_1> Entity_1s{ get; set; }
}
如何在實體2中建立具有外鍵(Entity_1)的連接?
一個Entity_1可以有多個Entity_2
這意味着Entity_1
(可選)具有Entity_2
的集合,而Entity_2
(可選)具有對Entity_1
的引用:
class Entity_1
{
public int Id { get; set; }
public virtual ICollection<Entity_2> Entity_2s{ get; set; }
}
class Entity_2
{
public int Id { get; set; }
public int Entity_1Id { get; set; }
public virtual Entity_1 Entity_1 { get; set; }
}
而您的實體不正確。 上面代碼的Fluent API是:
HasRequired(_ => _.Entity_1)
.WithMany(_ => _.Entity_2s)
.HasForeignKey(_ => _.Entity_1Id);
此處提供更多選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.