2017-09-29 74 views
2

我使用.NET Core 2.0。我寫了很多針對導航屬性,我知道這個時候不支持EF Core上的自動延遲加載。我使用微軟的方法來創建導航屬性。我試圖創建一個多對多的關係。如何在EF Core上創建自定義導航屬性

首先手動創建也包含在ApplicationDbContext像新的一樣DbSet

public class ProductCategory 
    { 
     [Key] 
     public int ProductId { get; set; } 
     [ForeignKey("ProductId")] 
     public virtual Product Product { get; set; } 

     [Key] 
     public int CategoryId { get; set; } 
     [ForeignKey("CategoryId")] 
     public virtual Category Category { get; set; } 
    } 

public class Product 
    { 
     public int Id { get; set; } 
     public virtual ICollection<ProductCategory> ProductCategory { get; set; 
    } 

    public class Category 
    { 
     public int Id { get; set; } 
     public virtual ICollection<ProductCategory> ProductCategory { get; set; 
    } 

在OnModelCreating類

  builder.Entity<ProductCategory>() 
      .HasKey(x => new { x.CategoryId, x.ProductId }); 

      builder.Entity<ProductCategory>() 
       .HasOne(x => x.Product) 
       .WithMany(x => x.ProductCategory) 
      .HasForeignKey(x => x.ProductId); 

      builder.Entity<ProductCategory>() 
       .HasOne(x => x.Category) 
       .WithMany(x => x.ProductCategory) 
      .HasForeignKey(x => x.CategoryId); 

當添加在映射表中的新對象映射表。

var productCategory = new ProductCategory 
      { 
       CategoryId = 1, 
       ProductId = 1 
      }; 

      db.ProductCategory.Add(productCategory); 
      db.SaveChanges(); 

項目已經成功添加,之後試圖訪問產品或類別測試導航屬性,但在映射只接收當前類table.You可以看到當我真的想從類別訪問產品的例子類:

model.Categories = this._categoryService 
       .All() 
       .Include(x => x.ProductCategory) 
       .ToList(); 

many-to-many-error-ef7

產品類爲null?

回答

2

這是因爲包括導航屬性自動包含反向導航屬性,但僅此而已。您需要特別要求使用ThenInclude

假設All方法返回IQueryable<Category>,這樣的事情:

model.Categories = this._categoryService 
       .All() 
       .Include(x => x.ProductCategory) 
        .ThenInclude(x => x.Product) 
       .ToList(); 

注意,這也將自動包括(負載)Product實體的ProductCategory集合屬性。

+0

我不能添加.ThenInclude(x => x.Product),因爲ProductCategory是枚舉,lambda上的x是枚舉。我試着用.ThenInclude(x => x.Select(x => x.Product)),但仍然無法使用! –

+1

@Dododov你試過的是EF6。以上的工作,VS智能感知剛出現問題。 'ThenInclude'有兩個重載 - 一個用於卷繞,一個用於參考。見https://stackoverflow.com/questions/45658411/ef-core-second-level-theninclude-missworks/45658984#45658984 –

+1

什麼是...現在是工作正常!非常感謝 ! –