.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();
Productクラスはnullですか?
ProductCategoryが列挙型であり、lambdaのxが列挙型であるため、.ThenInclude(x => x.Product)を追加できません。私はまた.ThenInclude(x => x.Select(x => x.Product))を使ってみましたが、まだ動作していません! –
@DTodorovあなたが試みたのはEF6です。上の作品は、ちょうどVS Intellisenseの既知の問題です。 'ThenInclude'には2つのオーバーロードがあります.1つはコイル選択用、もう1つは参照用です。 https://stackoverflow.com/questions/45658411/ef-core-second-level-theninclude-missworks/45658984#45658984 –
どういうわけか...はい、うまくいきました!どうもありがとう ! –