'How to use mapping inheritance and unflattening of the members?
I have the following classes:
public class Address
{
public string Street { get; set; }
public string ZipCode { get; set; }
//further address properties
public string BillingStreet { get; set; }
public string BillingZipCode { get; set; }
//further billing address properties
public string ShippingStreet { get; set; }
public string ShippingZipCode { get; set; }
//further shipping address properties
}
And:
public class Customer : Address
{
public string Name { get; set; }
}
The Address class is flattened as shown above because it is used to import records from a CSV file. I have many more classes just like Customer and I know I can use 'ForMember' to map individual members but doing so will make the mapping configuration too long and messy.
The destination classes are:
public class Address
{
public ParentType ParentType { get; set}
public AddressType AddressType { get; set}
public string Street { get; set; }
public string ZipCode { get; set; }
//further address properties
}
public class Customer
{
public string Name { get; set; }
public Address Address { get; set; }
public Address BillingAddress { get; set; }
public Address ShippingAddress { get; set; }
}
ParentType is an enum with values such as Customer, Supplier, etc. AddressType is also an enum with values Standard, Billing, Shipping.
Is it possible to configure AutoMapper in such a way to map the above successfully?
Solution 1:[1]
I believe you can use the .ForMember() Extention method as per below:
public class MyProfiles : Profile
{
public MyProfiles()
{
CreateMap<Customer, CustomerDto>()
.ForMember(x => x.BillingStreet, y => y.MapFrom(c => c.BillingAddress.Street))
.ForMember(x => x.BillingZipCode, y => y.MapFrom(c => c.BillingAddress.ZipCode))
.ForMember(x => x.ShippingStreet, y => y.MapFrom(c => c.ShippingAddress.Street))
.ForMember(x => x.ShippingZipCode, y => y.MapFrom(c => c.ShippingAddress.ZipCode));
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mohi |
