Entity Framework 中值为 null 时转换为默认值

Convert to default value when value is null in Entity Framework

我有以下 Entity Framework 查询,该查询有一个名为 byDateTime 列,它是从 MySQL 获得的,但有时它是 NULL,我得到一个错误

The specified conversion is invalid.

我知道我的模型已经解决了

public by? { get; set; }

但是我不想让它为nullable,我想知道有没有像[DefaultValue ()]这样的属性,表示如果得到一个null,就转成一个default值,即插入一个 DateTime.MinValue 以便不转换可为 null 的 datetime

var Context = new Context();

var docs = Context.Docs.AsNoTracking()
                  .Where(d => d.froms == "active")
                  .FirstOrDefault();

答案是否定的:检查可用的数据注释here。它用于核心,但也包含所有 EF 6 属性。

似乎 EF 强调即使进行值转换也不允许您这样做:https://docs.microsoft.com/en-us/ef/core/modeling/value-conversions

A null value will never be passed to a value converter. This makes the implementation of conversions easier and allows them to be shared amongst nullable and non-nullable properties.

这是有道理的,因为您正在有效地尝试绕过您自己添加到项目中的配置。

如果在您的数据库中有空值是有意义的,那么您的代码也应该有空值。

任何其他(非空)案例

Value converters allow property values to be converted when reading from or writing to the database.