簡體   English   中英

多對多 EF 核心 - 無法確定關系

[英]Many to many EF core - Unable to determine the relationship

我正在嘗試解決 EF 核心中的多對多關系,但我不斷收到異常(無法確定列表類型的導航屬性“Category.contacts”表示的關系)

我正在學習 EF 核心,我已經閱讀了很多關於這個問題的帖子,但我無法自己解決。 相信考試會問的。

我已經創建了一個類來解決多對多問題,但是如何使用 fluent api 正確配置它?

這是我的代碼:

public class Contact{
    public int PersonId {get; set;}
    public List<Category> Categories {get; set;}
}

public class Category{
    public int CategoryId {get; set;}
    public List<Category> Categories {get; set;}
}

public class ContactCategory{
    public int PersonId {get; set;}
    public int CategoryId {get; set;}
    public Contact Contact {get; set;}
    public Category Category {get; set;}
}

//Inside the DbContext class:
protected override void OnModelCreating(ModelBuilder modelBuilder){
    modelBuilder.Entity<ContactCategory>().HasKey(x => new {x.PersonId, x.CategoryId});
}

異常本身:

未處理的異常:System.TypeInitializationException:“Contacts.UI.CA.Program”的類型初始值設定項引發異常。 ---> System.InvalidOperationException: 無法確定由“List”類型的導航屬性“Category.Contacts”表示的關系。 手動配置關系,或使用“[NotMapped]”屬性或使用“OnModelCreating”中的“EntityTypeBuilder.Ignore”忽略此屬性。

多對多關系是一個棘手的關系。 我們需要了解這些關系是如何建立的。 通常,我們會構建兩個需要多對多關系的不同實體,創建一個實體,將純粹用於連接前兩個實體,然后在此實體之間進行一對多映射(創建用於連接兩個獨立的實體)一對多關系)和兩個實體(首先創建)分別:

public class Contact
{
    public int Id {get; set;}
    public ICollection<ContactCategory> ContactCategories {get; set;}
}

public class Category
{
    public int Id { get; set; }
    public ICollection<ContactCategory> ContactCategories { get; set; }
}

public class ContactCategory
{
    public int Id { get; set; }
    public int ContactId {get; set;}
    public Contact Contact {get; set;}
    public int CategoryId {get; set;}
    public Category Category {get; set;}
}

ContactCategory實體需要創建ContactCategory實體的多對多關系,它的唯一工作是連接 Contact 和 Category 實體。

我們應該在 Contact 和 ContactCategory 以及 Category 和 ContactCategory 實體之間的兩種不同的一對多關系中配置 Fluent API 中的關系。 HasForeignKey 方法不需要是通用的,因為一對多關系不需要顯式標記依賴類型:

Contact 和 Category 實體之間的多對多關系需要如下配置:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  modelBuilder.Entity<ContactCategory>()
    .HasOne(x => x.Category)
    .WithMany(x => x.ContactCategories)
    .HasForeignKey(x => x.CategoryId);

  modelBuilder.Entity<ContactCategory>()
    .HasOne(x => x.Contact)
    .WithMany(x => x.ContactCategories)
    .HasForeignKey(x => x.ContactId);
}

祝你好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM