簡體   English   中英

日期時間到可為空的日期時間轉換器自動映射器

[英]Datetime to nullable datetime converter automapper

我使用AutoMapper,但我的模型(使用EntityFramework)需要DateTime屬性,但我的POCO使用可為空的日期時間。

ItemModel.OtherDate.Year==1900ItemPOCO.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM