[英]EF Core Include() in Many to Many relation
Product和Customer之間的關系是多對多的類型(從設計角度來看)。
使用EF Core,我們將此關系與第三個實體( ProductCustomer)分成兩個一對多關系
public partial class ProductCustomer
{
public long ProductId { get; set; }
public long CustomerId { get; set; }
public virtual Customer Customer { get; set; }
public virtual Product Product { get; set; }
public virtual ICollection<UsageRecord> UsageRecord { get; set; }
}
UsageRecord是一個記錄列表,其中包含某個客戶在使用產品時使用的數據量
public partial class UsageRecord
{
public long Id { get; set; }
public long ProductId { get; set; }
public long CustomerId { get; set; }
public decimal Quantity { get; set; }
public virtual ProductCustomer ProductCustomer { get; set; }
}
現在,如果我嘗試讀取特定的UsageRecord ,則ProductCustomer對象為null (完美,我正在使用急切的加載方法)
return _usageRecordEntity.Where(x => x.ProductId == productId).AsEnumerable();
但是如果我特別要求Include() ProductCustomer實體,那么實體框架不僅包括所有遞歸引用,還包括Product對象而不是Customer !
return _usageRecordEntity.Where(x => x.ProductId == productId).Include(p => p.ProductCustomer).AsEnumerable();
第一件事:我不明白為什么它包括整個對象鏈如果我特別要求ProductCustomer一個。
第二件事:為什么是產品而不是顧客 ?!
我為完整性包含了Context模型:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>(entity =>
{
entity.Property(e => e.customerId)
.IsRequired()
.HasColumnName("CustomerId")
.HasMaxLength(255);
});
modelBuilder.Entity<Product>(entity =>
{
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50);
});
modelBuilder.Entity<ProductCustomer>(entity =>
{
entity.HasKey(e => new { e.ProductId, e.CustomerId })
.HasName("PK__ProductCustomerComposite");
entity.HasOne(d => d.Customer)
.WithMany(p => p.ProductCustomer)
.HasForeignKey(d => d.CustomerId)
.OnDelete(DeleteBehavior.Restrict)
.HasConstraintName("FK__ProductCu__CustomerId");
entity.HasOne(d => d.Product)
.WithMany(p => p.ProductCustomer)
.HasForeignKey(d => d.ProductId)
.OnDelete(DeleteBehavior.Restrict)
.HasConstraintName("FK__ProductCu__ProductId");
});
modelBuilder.Entity<UsageRecord>(entity =>
{
entity.Property(e => e.Quantity)
.HasColumnType("decimal")
.HasDefaultValueSql("0");
entity.HasOne(d => d.ProductCustomer)
.WithMany(p => p.UsageRecord)
.HasForeignKey(d => new { d.ProductId, d.CustomerId })
.OnDelete(DeleteBehavior.Restrict)
.HasConstraintName("FK_UsageRecordProductcustomer");
});
}
基本上,答案由加載相關數據中的以下提示提供- EF Core 文檔的 Eager加載部分(突出顯示是我的):
實體框架核心將自動將導航屬性修復到先前加載到上下文實例中的任何其他實體。 因此,即使您沒有明確包含導航屬性的數據,如果之前加載了部分或全部相關實體, 仍可能會填充該屬性 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.