The relationship between the Product and the Client is of the "many-to-many" type (from the design point - view).
Using EF Core, we divide this relationship into two one-to-many relationships with a third object: 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 is a list of records containing the amount of data used by a particular customer when he uses a product.
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; }
}
Now, if I try to read a specific UsageRecord, the ProductCustomer object will be null (fine, I use a high-load approach)
return _usageRecordEntity.Where(x => x.ProductId == productId).AsEnumerable();

But if I specifically ask the Include () ProductCustomer object, the entity framework not only includes all recursive links, but also includes the Product object and NOT Customer!
return _usageRecordEntity.Where(x => x.ProductId == productId).Include(p => p.ProductCustomer).AsEnumerable();

: ,
ProductCustomer.
: ?!
:
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");
});
}