简体   繁体   English

日期时间到可为空的日期时间转换器自动映射器

[英]Datetime to nullable datetime converter automapper

I use AutoMapper and I have a situation where my Model (use EntityFramework) require DateTime properties but my POCOs use nullable datetimes. 我使用AutoMapper,但我的模型(使用EntityFramework)需要DateTime属性,但我的POCO使用可为空的日期时间。

When ItemModel.OtherDate.Year==1900 the ItemPOCO.MyDate should be null . ItemModel.OtherDate.Year==1900ItemPOCO.MyDate应该为null

Any way to convert DateTime to Nullable DateTime with different property names? 有什么方法可以将DateTime转换为具有不同属性名称的Nullable DateTime?

I tried this, but it does not work: Property 'Int32 Year' is not defined for type 'System.Nullable'1[System.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)));
  }
}

错误信息

The problem ocurred in AutoMapper 5.0.2. 该问题发生在AutoMapper 5.0.2中。 I updated to version 5.1.1 and it's fine :) 我更新到版本5.1.1,也可以:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM