2017-09-29 7 views
2

.NET Core 2.0を使用しています。私は、この時点でEFコアでの自動遅延読み込みをサポートしていないことがわかっているナビゲーションプロパティのためにたくさん書きました。私はナビゲーションのプロパティを作成するMicrosoftのアプローチを使用しています。私は多対多の関係を作り出そうとしています。EFコアでカスタムナビゲーションプロパティを作成する方法

まずマッピングテーブルに新しいオブジェクトを追加する場合、新しい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); 

ようApplicationDbContextに含まれているテーブルをマッピング手動で作成します。

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

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

項目は、その後はtable.YouがI`mカテゴリから製品にアクセスしようとしている例を見ることができるナビゲーションプロパティをテストするために、製品またはカテゴリにアクセスしようとするが、マッピングでのみ現在のクラスを受け、正常に追加されますクラス:

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

many-to-many-error-ef7

Productクラスはnullですか?

答えて

2

これは、ナビゲーションプロパティを含めると自動的に逆ナビゲーションプロパティが含まれるためです。 ThenIncludeを使用して具体的に質問する必要があります。これはまた、自動的に(負荷)ProductエンティティのProductCategoryコレクションプロパティが含まれることを

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

注:All方法を想定し

は、このようなIQueryable<Category>、何かを返します。

+0

ProductCategoryが列挙型であり、lambdaのxが列挙型であるため、.ThenInclude(x => x.Product)を追加できません。私はまた.ThenInclude(x => x.Select(x => x.Product))を使ってみましたが、まだ動作していません! –

+1

@DTodorovあなたが試みたのはEF6です。上の作品は、ちょうどVS Intellisenseの既知の問題です。 'ThenInclude'には2つのオーバーロードがあります.1つはコイル選択用、もう1つは参照用です。 https://stackoverflow.com/questions/45658411/ef-core-second-level-theninclude-missworks/45658984#45658984 –

+1

どういうわけか...はい、うまくいきました!どうもありがとう ! –

関連する問題