我使用一个值对象来表示价格
public record Price(decimal Amount, string Currency);那么我有两个实体有一个价格
public class Item
{
public Price { get; private set; }
// rest of properties
}
public class OrderPosition
{
public Price { get; private set; }
// rest
}在DB中,我想要这两个表
Items
| Id | Price_Amount | Price_Currency |
OrderPositions
| Id | Price_Amount | Price_Currency |为此,我将Price配置为项目的所属类型以及订单位置:
public class ItemConfiguration : IEntityTypeConfiguration<Item>
{
public void Configure(EntityTypeBuilder<Item> builder)
{
builder.OwnsOne(i => i.Price);
}
}
public class ItemConfiguration : IEntityTypeConfiguration<OrderPosition>
{
public void Configure(EntityTypeBuilder<OrderPosition> builder)
{
builder.OwnsOne(op => op.Price);
}
}这一切都很好,但EF给了我一个警告,当我有相同的价格对一个项目以及在订单位置:
[09:47:59 WRN] The same entity is being tracked as different entity types 'Item.Price#Price' and 'OrderPosition.Price#Price' with defining navigations. If a property value changes, it will result in two store changes, which might not be the desired outcome.我完全理解这个例外,它甚至被记录为设计限制:https://learn.microsoft.com/en-us/ef/core/modeling/owned-entities#by-design-restrictions。
Instances of owned entity types cannot be shared by multiple owners (this is a well-known scenario for value objects that cannot be implemented using owned entity types).但是你如何解决这个问题呢?我是否需要为ItemPrice和OrderPositionPrice创建一个派生类,并相互间进行隐式转换?这是可行的,但我认为这不是最好的解决办法。
发布于 2022-10-04 11:27:10
有了前面提到的EF约束,重要的不是传递相同的值,而是传递它的副本。
public record Price(decimal Amount, string Currency)
{
public Price Copy() => new(this);
}
// used
var price = new Price(42.0, "USD");
item.Price = price.Copy();
orderPosition.Price = price.Copy();https://stackoverflow.com/questions/72123735
复制相似问题