![](/img/trans.png)
[英]Code First Entity Framework C#, Many to Many Mapping, Junction Table Created but list property not populated on object
[英]Entity Framework Junction(ish) Table Mapping Code FIrst
如何使用 EF v6.2 中的值映射連接表?
假設您有名為“Item1”、“Item2”的實體,並且映射了其中的另一個實體:
public class Item1
{
[Key]
public long Id { get; set; }
public virtual ICollection<MapItem> { get; set; }
}
public class Item2
{
[Key]
public int Id { get; set; }
public virtual ICollection<MapItem> { get; set; }
}
public class MapItem
{
public long Item1ID {get; set;} //PK, FK
public int Item2ID {get; set;} //PK, FK
public decimal Value {get; set;}
public string Name {get; set;}
public virtual Item1 {get; set;}
public virtual Item2 {get; set;}
}
EDMX 會自動生成它,但是我將如何使用代碼優先 / FluentAPI 構建它來構建MapItem
實體的可訪問集合?
我嘗試更新映射實體以在MapItem
的 PK 和 FK 值上使用[Key(Order = 1)]
和[Key(Order = 2)]
。
考慮到它不是 2 個實體的真正聯結表,但它也具有價值,這似乎是一個奇怪的場景。
在這里,我能夠使用 FluentAPI 解決它。
這里我修改了實體類:
public class MapItem
{
[Key(Order = 1)]
public long Item1ID {get; set;} //PK, FK
[Key(Order = 2)]
public int Item2ID {get; set;} //PK, FK
public decimal Value {get; set;}
public string Name {get; set;}
public virtual Item1 {get; set;}
public virtual Item2 {get; set;}
}
然后在關系構建器中:
modelBuilder.Entity<MapItem>().HasKey(q => new
{
q.Item1ID, q.Item2ID
});
modelBuilder.Entity<MapItem>().HasRequired(q => q.Item1).WithMany(q => q.MapItem).HasForeignKey(q => q.Item1ID);
modelBuilder.Entity<MapItem>().HasRequired(q => q.Item2).WithMany(q => q.MapItem).HasForeignKey(q => q.Item2ID);
關鍵部分是正確映射實體的“HasKey”方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.