[英]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.