automap使用automapper将复杂类型列表复杂类型列表

时间:2016-08-10 19:09:10

标签: c# automapper

public class SourceExamModel
{
    public int ExamId { get; set; }      

    public List<SectionModel> Sections { get; set; }
}

public class  DesiationExamModel
{
public in ExamId {get;set;}
public System.Collections.Generic.IEnumerable<SectionModel> DestSections
{
    get
    {
    }
    set
    {
    }
}

我尝试了什么:

var config = new MapperConfiguration(cfg => {
    cfg.CreateMap<CrmMapper.SourceExamModel, CrmMapper.DestiationExamModel>()
    .ForMember(v => v.Id, opts => opts.MapFrom(src => src.Id))
    .ForMember(v => v.DestSections, opts => opts.MapFrom(src => src.SourceSections));      
});

IMapper mapper = config.CreateMapper();
var source = new ExamModel();
var dest = mapper.Map<SourceExamModel, CrmMapper.DestiationExamModel>(source);

可以帮助我如何映射复杂对象的复制对象列表

1 个答案:

答案 0 :(得分:0)

假设您的示例代码中有一半是简单的拼写错误,那么您几乎可以使用它。

  1. 如果源和目标上的属性名称相同,则不必明确映射它们。
  2. 您的示例中的source没有意义,它需要正确的对象和数据。
  3. 这是我尝试的一个工作示例,您可以将其复制到控制台应用程序中。

    class Program
    {
        static void Main(string[] args)
        {
            var config = new MapperConfiguration(cfg =>
                cfg.CreateMap<SourceExamModel, DestinationExamModel>()
                    .ForMember(dest => dest.DestSections, c => c.MapFrom(src => src.Sections))
            );
    
            config.AssertConfigurationIsValid();
            var mapper = config.CreateMapper();
    
            var source = new SourceExamModel
            {
                ExamId = 1,
                Sections = new List<SectionModel> { new SectionModel { SectionId = 1 }, new SectionModel { SectionId = 2 } }
            };
    
            var destination = mapper.Map<SourceExamModel, DestinationExamModel>(source);
        }
    }
    
    public class SourceExamModel
    {
        public int ExamId { get; set; }
    
        public List<SectionModel> Sections { get; set; }
    }
    
    public class DestinationExamModel
    {
        public int ExamId { get; set; }
    
        public List<SectionModel> DestSections { get; set; }
    }
    
    public class SectionModel
    {
        public int SectionId { get; set; }
    }