Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 来自can的自动映射';不接受空值_C#_Sql_.net Core_Automapper_Mysql.data - Fatal编程技术网

C# 来自can的自动映射';不接受空值

C# 来自can的自动映射';不接受空值,c#,sql,.net-core,automapper,mysql.data,C#,Sql,.net Core,Automapper,Mysql.data,我的person数据库表中有一列session\u expires\u在。此列的类型为DATETIME,可为空。在我的代码中,我的User对象用 public DateTime? SessionExpiresAt { get; set; } 当使用MySQL.Data包从数据库中读取用户时,我想使用AutoMapper将数据库结果映射到user对象 CreateMap<DbDataReader, User>() .ForMember(user => user.Sess

我的
person
数据库表中有一列
session\u expires\u在
。此列的类型为
DATETIME
,可为空。在我的代码中,我的
User
对象用

public DateTime? SessionExpiresAt { get; set; }
当使用MySQL.Data包从数据库中读取用户时,我想使用AutoMapper将数据库结果映射到
user
对象

CreateMap<DbDataReader, User>()
    .ForMember(user => user.SessionExpiresAt,
        memberOptions => memberOptions.MapFrom(dbDataReader => dbDataReader.IsDBNull(1) ? null : dbDataReader.GetDateTime(1)));
我得到这个错误

无法从用法推断类型参数。尝试指定 类型参数被显式删除

我也试过了,但没用

CreateMap<DbDataReader, User>()
    .ForMember(user => user.SessionExpiresAt,
        memberOptions =>
        {
            memberOptions.AllowNull();
            memberOptions.MapFrom(dbDataReader => dbDataReader.GetDateTime(1));
        });
CreateMap()
.ForMember(user=>user.SessionExpiresAt,
memberOptions=>
{
memberOptions.AllowNull();
memberOptions.MapFrom(dbDataReader=>dbDataReader.GetDateTime(1));
});
如果数据库值为空,则无法使用默认值,如
DateTime.Now
。必须能够分配空值


如何修复它,以便在映射规则中为属性分配空值?如果值为null,也许我可以禁用映射过程,这样它就不会赋值了?

正如其他人在评论中已经提到的,您的
MapFrom()
逻辑无法工作,因为
null
DateTime
之间的类型不匹配,因为
DateTime
不能是
null
。只有可为空的
DateTime
可以,因此您应该使用
(DateTime)null
默认值(DateTime?
而不是使用
null

CreateMap()
福门博先生(
user=>user.SessionExpiresAt,
options=>options.MapFrom(dbDataReader=>dbDataReader.IsDBNull(1)?默认值(DateTime?):dbDataReader.GetDateTime(1));
另一种方法是使用
predition()
,在实际映射之前,您可以检查reader中的特定值是否为null,这可能更具可读性。如果是,则不会发生
SessionExpiresAt
的映射

CreateMap()
福门博先生(
user=>user.SessionExpiresAt,
选项=>
{
先决条件(dbDataReader=>!dbDataReader.IsDBNull(1));
options.MapFrom(dbDataReader=>dbDataReader.GetDateTime(1));
});

为什么要投否决票?至少请不要发表评论。我不能设置一个默认值,比如
,如果为空,则使用DateTime。现在
或类似的东西。该属性可为null,并且数据库中的值可能为null。重要的一点是,您需要在数据库中使用
(DateTime?)null
CreateMap<DbDataReader, User>()
    .ForMember(user => user.SessionExpiresAt,
        memberOptions =>
        {
            memberOptions.AllowNull();
            memberOptions.MapFrom(dbDataReader => dbDataReader.GetDateTime(1));
        });