简体   繁体   中英

Map List of Customers with automapper

Using Automapper I am trying to map one object to another. One property is a class called Task containing a list of customers. The other class is called Result and contains a count of customers as well as another list of customers.

This is my current approach which fills information into the order properties correctly, but fails in result, which is still null. How can I get the List into result? How do i need to change the maps and do i need to create a map in both directions, or this this not necessary?

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

here are my current classes (Customer):

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

Okay so the solution to my problem was that my mapping didn't find "result" so i've just mapped my RootObject like this:

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()));

then i went ahead and just mapped the result like this:

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

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

and just bound it to a new Customerobject. Then all my information got transmitted as expected

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM