根据条件自动映射两个对象

时间:2020-01-14 01:25:48

标签: c# json automapper

试图弄清楚AutoMapperCustomer模型的映射是否可行 到Address的列表中,其中客户中的CustomerDetails值与地址中的ID匹配?

CustomerID

最终目标是拥有以下Json对象

public class Customer {
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string Surname { get; set; }
}

public class Address {
    public int ID { get; set;}
    public int CustomerID { get; set; }
    public string Address1 { get; set; }
    public string Address2  { get; set; }
    public string Town { get; set; }
    public string PostCode { get; set; }
}

public class CustomerDetails{
    public int ID { get; set; }
    public Customer CustomerInfo { get; set; }
    public Address CustomerAddress { get; set; }
}

到目前为止,我只能想到以下AutoMapper配置

{
  ID: 1234,  
  CustomerInfo: {
      ID: 1,
      FirstName: "John",
      Surname: "Connor"   
  }
  CustomerAddress: {
      ID: 1232,
      CustomerID: 1,
      Address1: "123 Avenue",
      Address2: "Some road",
      Town: "London",
      PostCode: "L1WLL"
  }  
}

用法

Mapper.CreateMap<Customer, CustomerDetails>();
Mapper.CreateMap<Address, CustomerDetails>()

1 个答案:

答案 0 :(得分:0)

您可以根据客户ID将这两个集合组合成一个元组类型(客户,地址),并将该类型映射到CustomerDetail类型。

CreateMap<(Customer cust, Address addr), CustomerDetails>();
customers.Select(r => (r, addresses.FirstOrDefault(a => a.CustomerID == r.ID))).Select(g => mapper.Map(g));

您还可以分两个阶段进行映射,首先将客户映射到客户详细信息,然后将地址映射到客户详细信息:

        CreateMap<Customer, CustomerDetails>()
            .ForMember(d => d.ID, opt => opt.MapFrom(s => s.ID))
            .ForMember(d => d.CustomerInfo, opt => opt.MapFrom(s => s))
            .ForAllOtherMembers(opt => opt.Ignore());

        CreateMap<Address, CustomerDetails>()
            .ForMember(d => d.CustomerAddress, opt => opt.MapFrom((s, d) => d.ID == s.CustomerID ? s : d.CustomerAddress))
            .ForAllOtherMembers(opt => opt.Ignore());

        CreateMap<Address, IEnumerable<CustomerDetails>>()
            .ConvertUsing((a, d, ctx) =>
            {
                CustomerDetails match = d.FirstOrDefault(c => c.ID == a.CustomerID);
                if (match != null) 
                {
                    ctx.Mapper.Map(match, a);
                }

                return d;
            });

映射:

List<Customer> customers = new List<Customer>();
List<Address> addresses = new List<Address>();
var result = mapper.Map<List<CustomerDetails>>(customers);
addresses.ForEach(a => mapper.Map(a, result));