使用automapper映射客户列表

时间:2017-05-04 12:59:56

标签: c# .net automapper automapper-6

使用Automapper我试图将一个对象映射到另一个对象。一个属性是一个名为Task的类,其中包含一个客户列表。另一个类称为Result,包含一组客户以及另一个客户列表。

这是我当前的方法,它正确地将信息填充到订单属性中,但结果失败,结果仍为空。如何将List列入结果?我如何更改地图,是否需要在两个方向上创建地图,或者这不是必需的?

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<CustomerPost.RootObject, Customers.RootObject>();

    cfg.CreateMap<CustomerPost.Order, Customers.Order>();

    cfg.CreateMap<Customers.Result, CustomerPost.Task>();                   
    cfg.CreateMap<CustomerPost.Task, Customers.Result>()
        .ForMember(x => x.customerscount, opt => opt.Ignore())
        .ForMember(x => x.customerstotalcount, opt => opt.Ignore());
});
try
{
    Mapper.AssertConfigurationIsValid();
}
catch (AutoMapperConfigurationException ex)
{
    //TODO: Handle this
    throw ex;
}

var customer = Mapper.Map<CustomerPost.RootObject, Customers.RootObject>(input);

这是我目前的课程(客户):

    public class Result
    {
        public int customerstotalcount { get; set; }
        public int customerscount { get; set; }
        public List<Customer> customers { get; set; }
    }

    public class RootObject
    {
        public Status status { get; set; }
        public Order order { get; set; }
        public Result result { get; set; }
    }

CustomerPost:

    public class Task
    {
        public List<Customer> customers { get; set; }
    }

    public class RootObject
    {
        public Order order { get; set; }
        public List<Task> tasks { get; set; }
    }

1 个答案:

答案 0 :(得分:0)

好的,我问题的解决方案是我的映射没有找到&#34;结果&#34;所以我刚刚映射了我的RootObject:

Mapper.Initialize(cfg =>
                        {
                            cfg.CreateMap<CustomerPost.RootObject, Customers.RootObject>()
                                .ForMember(x => x.status, opt => opt.Ignore())
                                .ForMember(x => x.order, opt => opt.Ignore())
                                .ForMember(dest => dest.result, src => src.MapFrom(opt => opt.tasks.FirstOrDefault()));

然后我继续前进,只是映射了这样的结果:

var result = Mapper.Map<CustomerPost.Task, Customers.Result>(input.tasks.FirstOrDefault());

var customer = new Customers.Customer();
customer = result.customers.FirstOrDefault();

并将其绑定到新的Customerobject。然后我的所有信息都按预期传输了