自动映射器和实体框架映射复杂的关系建议

时间:2019-04-24 07:30:37

标签: c# list automapper hashset flatten

我正在尝试映射一个复杂的实体类型,并在涉及嵌套关系时碰壁。

基本上这是我的EF实体:

 public partial class LDT001002_FILE_MST
    {
        public LDT001002_FILE_MST()
        {
            this.LDT001201_FILE_STATUS_DTL = new HashSet<LDT001201_FILE_STATUS_DTL>();
    ... }
        public virtual ICollection<LDT001201_FILE_STATUS_DTL> LDT001201_FILE_STATUS_DTL { get; set; }

这是LDT001201_FILE_STATUS_DTL:

    public partial class LDT001201_FILE_STATUS_DTL
    {
        public System.Guid FILE_STATUS_DTL_ID { get; set; }
    ...
    }

这是与自动映射器一起使用的视图模型:

 public class GeneralInformation
    {
    ...
        public List<FileStatuses> FileStatuses { get; set; }
    ...
    }

  public class FileStatuses : GeneralInformation { 

        public Guid FILE_STATUS_DTL_ID { get; set; }
        [DisplayName("Date Initiated")]

}

I tried multiple CreateMap configurations but all throw unmapped errors about the object on Mapper.Map for these 2 models... any suggestions from Automapper veterans are welcome!

1 个答案:

答案 0 :(得分:1)

解决方案:

  1. 将哈希集映射到列表 GeneralInformation>()
cfg.CreateMap<LDT001002_FILE_MST, 
    .ForMember(dest => dest.FileStatus, opt => opt.MapFrom(
        src => src.LDT001201_FILE_STATUS_DTL));
  1. 将外部引用映射到列表:
 cfg.CreateMap<LDT001201_FILE_STATUS_DTL, FileStatuses>()
    .ForMember(dest => dest.LOC_ID, opt => opt.MapFrom(src => src.LDT001013_LOC_MST.LOC_ID))
    .ForMember(dest => dest.LOC_NM, opt => opt.MapFrom(src => src.LDT001013_LOC_MST.LOC_NM))
    .ForMember(dest => dest.STATUS_ID, opt => opt.MapFrom(src => src.LDT001601_STATUS_LKP.STATUS_ID))
    .ForMember(dest => dest.STATUS_NM, opt => opt.MapFrom(src => src.LDT001601_STATUS_LKP.STATUS_NM));