0

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

这是我目前的方法,可以正确地将信息填充到订单属性中,但结果失败,结果仍然为空。我怎样才能把列表变成结果?我需要如何更改地图,我是否需要在两个方向上创建地图,或者这没有必要?

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; }
    }

客户邮局:

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

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

1 回答 1

0

好的,我的问题的解决方案是我的映射没有找到“结果”,所以我只是像这样映射了我的 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();

并将其绑定到一个新的客户对象。然后我的所有信息都按预期传输

于 2017-05-05T07:22:18.093 回答