[英]Many to Many relationship EF with foreign keys
我想配置2個實體之間的多對多關系,但我也想公開它們的外鍵。 我在網上僅找到一種具體的解決方案,如下所示:
modelBuilder.Entity<E1>()
.HasMany(t => t.E1s)
.WithMany(t => t.E2s)
.Map(m =>
{
m.ToTable("E1E2");
m.MapLeftKey("FKE1");
m.MapRightKey("FKE2");
});
但是地圖的左右鍵不會從我的模型中獲取屬性,因此我無權訪問它們,並且在查詢時不會填充它們。 因此,我無權訪問我的外鍵屬性。
希望我能解釋我的問題。 有人可以建議其他選擇嗎?
您可以創建一個具有兩個實體中的鍵的關聯模型:
public class AssociativeEntity
{
[Key]
public Guid AssociativeEntityId { get; set; }
public Guid Entity1Id { get; set; }
public Guid Entity2Id { get; set; }
[Display(Name = "Entity1", ResourceType = typeof(Resources.Language))]
public virtual Entity1 Entity1 { get; set; }
[Display(Name = "Entity2", ResourceType = typeof(Resources.Language))]
public virtual Entity2 Entity2 { get; set; }
}
實體1:
public class Entity1
{
[Key]
public Guid Entity1Id { get; set; }
/* Describe the other properties here */
[Display(Name = "AssociativeEntities", ResourceType = typeof(Resources.Language))]
public virtual ICollection<AssociativeEntity> AssociativeEntities { get; set; }
}
實體2:
public class Entity2
{
[Key]
public Guid Entity2Id { get; set; }
/* Describe the other properties here */
[Display(Name = "AssociativeEntities", ResourceType = typeof(Resources.Language))]
public virtual ICollection<AssociativeEntity> AssociativeEntities { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.