我正在使用.NET Core 2.0。我写了很多导航属性,我知道目前 EF Core 上不支持自动延迟加载。我正在使用 Microsoft 方法来创建导航属性。我正在尝试创建多对多关系。
首先创建手动映射表,该表也像新的 DbSet 一样包含在 ApplicationDbContext 中
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();
项目添加成功,之后尝试访问产品或类别来测试导航属性,但仅接收映射表中的当前类。您可以看到我尝试从类别类访问产品时的示例:
model.Categories = this._categoryService
.All()
.Include(x => x.ProductCategory)
.ToList();
产品类别为空?
最佳答案
这是因为包含导航属性会自动包含反向导航属性,仅此而已。您需要使用 ThenInclude
特别询问。 .
假设All
方法返回 IQueryable<Category>
,像这样:
model.Categories = this._categoryService
.All()
.Include(x => x.ProductCategory)
.ThenInclude(x => x.Product)
.ToList();
请注意,这还将自动包含(加载)ProductCategory
Product
的集合属性实体。
关于asp.net-core - 如何在 EF Core 上创建自定义导航属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46488150/