datetime可以为null的datetime转换器automapper

时间:2016-08-12 12:18:21

标签: c# entity-framework datetime mapping 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)));
  }
}

Error message

1 个答案:

答案 0 :(得分:1)

AutoMapper 5.0.2中出现问题。我更新到5.1.1版本,它很好:)

相关问题