EF Core 转换和不可空类型转换为可空基元

EF Core conversion and non nullable type converted to a nullable primitive

我有一个 class MyClass 有一个不可为 null 的 属性 Maybe<int> MyMproperty.

#nullable enable
public class MyClass
{
    public long Id { get; set; }
    public Maybe<int> MyProperty { get; set; }
}
#nullable restore

我在 MyContext:

中声明并使用 en EF 转换
builderEntity.Property(o => o.MyProperty).HasMaybeIntConversion();


public static PropertyBuilder<Maybe<int>> HasMaybeIntConversion(this PropertyBuilder<Maybe<int>> property)
        => property.HasConversion(
            x => x.Select(i => (int?)i).GetValueOrFallback(null),
            x=> x.HasValue 
                ? Maybe.From(x.Value) 
                : Maybe<int>.None);

想法是坚持 null Maybe.None 并从 null.

加载 Maybe.None

但是这不起作用。当 EF 在数据库中看到 null 时,它会在不使用转换规则的情况下将 null 设置为 MyProperty(不可为空)。

要使其正常工作,我必须进行以下更改:

#nullable enable
public class MyClass
{
    public long Id { get; set; }
    public Maybe<int> MyProperty => MyPropertyNullable  ?? Maybe<int>.None;
    public Maybe<int>? MyPropertyNullable { get; set; }
}
#nullable restore

并在 MyContext 中:

builderEntity.Property(o => o.MyPropertyNullable).HasMaybeIntConversion().HasColumnName(nameof(MyClass.MyProperty));

我觉得它又重又丑。

有人知道实现相同结果的更简单方法吗?

不幸的是,这是 EF Core 的限制。如果基础数据库列可以为空,则映射的 属性 也必须可以为空。
如果从数据库中获取的值为null,EF会完全跳过注册的转换方法。

已跟踪问题 here

value converters do not generally allow the conversion of null to some other value. This is because the same value converter can be used for both nullable and non-nullable type.