首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >EF核心价值对象

EF核心价值对象
EN

Stack Overflow用户
提问于 2022-05-05 07:51:30
回答 1查看 398关注 0票数 0

我使用一个值对象来表示价格

代码语言:javascript
复制
public record Price(decimal Amount, string Currency);

那么我有两个实体有一个价格

代码语言:javascript
复制
public class Item 
{
    public Price { get; private set; }
    // rest of properties
}

public class OrderPosition 
{
    public Price { get; private set; }
    // rest
}

在DB中,我想要这两个表

代码语言:javascript
复制
Items
| Id | Price_Amount | Price_Currency |


OrderPositions
| Id | Price_Amount | Price_Currency |

为此,我将Price配置为项目的所属类型以及订单位置:

代码语言:javascript
复制
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给了我一个警告,当我有相同的价格对一个项目以及在订单位置:

代码语言:javascript
复制
[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

代码语言:javascript
复制
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创建一个派生类,并相互间进行隐式转换?这是可行的,但我认为这不是最好的解决办法。

EN

回答 1

Stack Overflow用户

发布于 2022-10-04 11:27:10

有了前面提到的EF约束,重要的不是传递相同的值,而是传递它的副本

代码语言:javascript
复制
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();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72123735

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档