c# - EF Core - 用于简单 ValueObject 的 ValueConverter 或 OwnedType?

标签 c# entity-framework-core value-objects valueconverter owned-types

我使用值对象来封装像 maxLength 这样的验证。这是没有工厂方法和验证的示例类的摘录:

public class CallingName : ValueObject
{
    public string Value { get; }
    public const int MaxLength = 50;

    private CallingName(string text)
    {
        Value = text;
    }
   ...
 }

在 SQL 数据库中,表应具有 nvarchar 类型的字段“CallingName”,最大长度为 50。

使用 EF Core 我知道值转换器和拥有的类型,但我不完全理解两者之间的选项和差异。如果值对象只有一个属性,是否可以使用其中之一?

到目前为止,我为该字段使用了值转换器:

entity.Property(e => e.CallingName)
    .HasMaxLength(CallingName.MaxLength)
    .HasConversion(DBConverter.CallingNameConverter);

查看 Microsoft docs 中的简单示例我认为这应该在没有像这样的值转换器的情况下工作

entity.OwnsOne(e => e.CallingName)
     .Property(e => e.Value)
     .HasColumnName("CallingName")
     .HasMaxLength(CallingName.MaxLength);

entity.OwnsOne(e => e.CallingName, 
     p=>p.Property<string>("CallingName")
     .HasMaxLength(CallingName.MaxLength));

entity.OwnsOne(e => e.CallingName, 
     p => p.Property(e=>e.Value)
    .HasColumnName("CallingName")
    .HasMaxLength(CallingName.MaxLength));

以上版本都可以用吗?不同版本的目的是什么?使用值转换器或自有类型的情况或标准是什么?

据我了解,当类型没有公共(public) setter 时,它们需要为拥有的类型提供一个空的构造函数。值转换器可以分别调用构造函数。工厂方法。这是正确的吗?

documentation for OwnsOne显示 6 个重载,但没有示例。这些描述对我来说听起来是克林贡语。我不明白每一个是做什么用的。我找不到更好的解释或谷歌搜索文章。有没有很好的例子解释?

最佳答案

我也在 dotnet core issues 中发布了这个问题 github 。 ajcvickers 回答:

Owned types are entity types that have a key property and are identified by the value of that key. (EF may hide this key value from you, but it is still there and affects the semantics of the how the objects are used.) In DDD terms, they are intended to support aggregates, with the owner acting as the aggregate root. They do not work very well for DDD value objects since they are identified by a key, which goes against the principle of value objects.

Using a value converter means that the property is still mapped as a property, and does not have a key. This means that properties with a value converter inherently have value object semantics, and so are a much better fit than owned types.

据我了解,在 EF Core 7 之前,自有类型仍然是具有多个属性的值对象的唯一选择。

我仍然没有找到 OwnsOne 重载的解释以及为什么要使用每个重载。

关于c# - EF Core - 用于简单 ValueObject 的 ValueConverter 或 OwnedType?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71619005/

相关文章:

c# - 如何在 Entity Framework Core 2.0 中的模型本身内部使用 OnModelCreating?

entity - 领域驱动设计 - 值对象或实体

PHP OOP 概念(值对象/数据访问对象)

c# - union 结构 C# - 等效或等于?

c# - 如何使用对象中指定的行/列将 `ObservableCollection` 绑定(bind)到网格?

c# - EF Core 2.1.0 设置默认字符串长度和列类型

domain-driven-design - DDD,值对象和ORM

c# - 我怎样才能找出哪个对象创建了这个对象

c# - linq to sql提交更改不起作用

postgresql - 使用 EF Core 5 查询 Postgres Json 字段