[英]Datetime to nullable datetime converter automapper
我使用AutoMapper,但我的模型(使用EntityFramework)需要DateTime属性,但我的POCO使用可为空的日期时间。
当ItemModel.OtherDate.Year==1900
, ItemPOCO.MyDate
应该为null
。
有什么方法可以将DateTime转换为具有不同属性名称的Nullable DateTime?
我尝试了此操作,但它不起作用: Property 'Int32 Year' is not defined for type 'System.Nullable'1[System.DateTime]'
// Class Model (EntityFramework)
public class ItemModel{
public DateTime OtherDate { get; set; }
}
// POCO
public class ItemPOCO{
public DateTime? MyDate { get; set; }
}
// AutoMapper Profile
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<ItemModel, ItemPOCO>()
.ForMember(poco => poco.MyDate,
opt => opt.MapFrom(m => m.OtherDate.Year == 1900 ? null : new DateTime?(m.OtherDate)));
}
}
该问题发生在AutoMapper 5.0.2中。 我更新到版本5.1.1,也可以:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.