![](/img/trans.png)
[英]EF Core: Can I map nullable SQL type to non-nullable value type in my Entity?
[英]EF Core conversion and non nullable type converted to a nullable primitive
我有一個MyClass
類,它有一個不可為空的屬性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);
這個想法是為Maybe.None
保留null
並從null
加載Maybe.None
。
然而這行不通。 當 EF 在數據庫中看到null
時,它會在不使用轉換規則的情況下將null
設置為MyProperty
(不可為 null)。
為了使其工作,我必須進行以下更改:
#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 將完全跳過注冊的轉換方法。
該問題在此處進行了跟蹤。
值轉換器通常不允許將 null 轉換為其他值。 這是因為相同的值轉換器可用於可為空類型和不可為空類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.