自动映射器映射到可为null的DateTime属性 [英] Automapper map to nullable DateTime property

查看:76
本文介绍了自动映射器映射到可为null的DateTime属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Automapper 3.1.1,我无法编译此映射:

using Automapper 3.1.1 I can not compile this map:

Mapper.CreateMap<Domain.DomainObjects.Entities.Patient, PatientDto>()
                .ForMember(x => x.Deleted, opt => opt.MapFrom(input => input.Deleted.HasValue ? 
                    new DateTime(input.Deleted.Value.Ticks, DateTimeKind.Utc) : null ));

错误:

条件表达式的类型无法确定,因为'< null>'之间没有隐式转换和"DateTime"

实体:

public class Patient : Entity
{
        // more properties
        public virtual DateTime? Deleted { get; set; }
}

感觉就像我遗漏了一些明显的东西,但无法确切地知道到底是什么.

Feel like I am missing something obvious but can not figure out what exactly.

注意:Dto包含 DateTime?也删除了

推荐答案

我尚未测试,但是您只需要将 null 强制转换为 DateTime?.((DateTime?)null )

I haven't tested, but you should just need to explicitly cast null to a DateTime?. ((DateTime?)null)

Mapper.CreateMap<Domain.DomainObjects.Entities.Patient, PatientDto>()
                .ForMember(x => x.Deleted, opt => opt.MapFrom(input => input.Deleted == null ? (DateTime?)null : (
                new DateTime(input.Deleted.Value.Ticks, DateTimeKind.Utc))));

这篇关于自动映射器映射到可为null的DateTime属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆