比方说,我有一个产品 A,其价格通常为10,但对于客户 X,其价格为8。我想将这些信息存储为价格< / strong>表/类(因为它们共享其他属性和方法)。
当“ ClientId”为null时,表示我具有“ ProductId”的默认价格,否则为该“ ClientId”的特定价格。
因此,我设置了以下实体:
// owned type
public class Price
{
public Guid Id { get; private set; }
public Guid ProductId { get; private set; }
public Guid? ClientId { get; private set; }
public decimal Value { get; private set; }
// ... some other properties and methods
}
// 1st owner
public class Product
{
public Guid Id { get; private set; }
public List<Price> Prices { get; private set; }
// ...
}
// 2nd owner
public class Client
{
public Guid Id { get; private set; }
public List<Price> Prices { get; private set; }
// ...
}
及其映射:
// 1st owner mappings
public class ProductMap : EntityMappings<Product>
{
public override void Configure(EntityTypeBuilder<Product> entity)
{
base.Configure(entity);
entity.ToTable("product");
entity.Property(e => e.Id).HasColumnName("id").HasColumnType("uuid").ValueGeneratedNever();
// this part is identical for both owners
entity.OwnsMany(e => e.Prices, child =>
{
child.ToTable("price");
child.Property(e => e.Id).HasColumnName("id").HasColumnType("uuid").ValueGeneratedNever();
child.Property(e => e.Value).HasColumnName("value").HasColumnType("numeric(10,2)");
child.Property(e => e.ProductId).HasColumnName("product_id").HasColumnType("uuid");
child.Property(e => e.ClientId).HasColumnName("client_id").HasColumnType("uuid");
child.HasKey(e => e.Id).HasName("pk-price");
child.HasForeignKey(e => e.ProductId)
.OnDelete(DeleteBehavior.Restrict)
.HasConstraintName("fk-price-product");
child.HasForeignKey(e => e.ClientId)
.OnDelete(DeleteBehavior.Restrict)
.HasConstraintName("fk-price-client");
});
entity.HasKey(e => e.Id).HasName("pk-product");
}
}
// 2nd owner mappings
public class ClientMap : EntityMappings<Client>
{
public override void Configure(EntityTypeBuilder<Client> entity)
{
base.Configure(entity);
entity.ToTable("client");
entity.Property(e => e.Id).HasColumnName("id").HasColumnType("uuid").ValueGeneratedNever();
// this part is identical for both owners
entity.OwnsMany(e => e.Prices, child =>
{
child.ToTable("price");
child.Property(e => e.Id).HasColumnName("id").HasColumnType("uuid").ValueGeneratedNever();
child.Property(e => e.Value).HasColumnName("value").HasColumnType("numeric(10,2)");
child.Property(e => e.ProductId).HasColumnName("product_id").HasColumnType("uuid");
child.Property(e => e.ClientId).HasColumnName("client_id").HasColumnType("uuid");
child.HasKey(e => e.Id).HasName("pk-price");
child.HasForeignKey(e => e.ProductId)
.OnDelete(DeleteBehavior.Restrict)
.HasConstraintName("fk-price-product");
child.HasForeignKey(e => e.ClientId)
.OnDelete(DeleteBehavior.Restrict)
.HasConstraintName("fk-price-client");
});
entity.HasKey(e => e.Id).HasName("pk-client");
}
}
这给了我错误
不能将表“ price”用于实体类型“ Client.Prices#Price”,因为它已用于实体类型“ Product.Prices#Price”,并且它们的主键之间没有关系。
但是我不知道如何关联他们的PK,因为它们在双方都是相同的实体/类。
有没有办法做到这一点?还是建议一种更好的方法来避免重复在 Price 实体中找到的行为(和表结构)?