Class Customer
public class Customer
{
public int Id { get; set; }
public int PersonId { get; set; }
public int DiscountValue { get; set; }
public Person Person { get; set; }
public ICollection<Receipt> Receipts { get; set; }
}
Class Person
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public DateTime BirthDate { get; set; }
}
Class CustomerModel
public class CustomerModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public DateTime BirthDate { get; set; }
public int DiscountValue { get; set; }
public ICollection<int> ReceiptsIds { get; set; }
}
I need to create mapping that combines Customer
and Person
into CustomerModel
.
public class AutomapperProfile : Profile
{
public AutomapperProfile()
{
CreateMap<(Customer, Person), CustomerModel>();
}
}
How can I combine Customer and Person?
CodePudding user response:
You can just map from Customer
to CustomerModel
as:
Solution 1: Specify the property mapping from source to destination via .ForMember()
.
CreateMap<Customer, CustomerModel>()
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Person.Name))
.ForMember(dest => dest.Surname, opt => opt.MapFrom(src => src.Person.Surname))
.ForMember(dest => dest.BirthDate, opt => opt.MapFrom(src => src.Person.BirthDate));
Solution 2: Flattening Person
model via .IncludeMembers()
.
cfg.CreateMap<Customer, CustomerModel>()
.IncludeMembers(src => src.Person);
cfg.CreateMap<Person, CustomerModel>();