I'm kinda new to Automapper so I might try to use it for something it shouldn't be used for, but here it goes. I have two classes :
public class Container
{
public int Id { get; set; }
public string Code { get; set; }
public string StrVal { get; set; }
public DateTime Date { get; set; }
public Containee Containee { get; set; }
}
public class Containee
{
public int Id { get; set; }
public decimal Value { get; set; }
public string DifferentStr { get; set; }
public DateTime birthday { get; set; }
}
And I have a DTO that looks like this :
public class ContaineeDTO
{
public int Id { get; set; }
public decimal Value { get; set; }
public string DifferentStr { get; set; }
public DateTime birthday { get; set; }
public string Code { get; set; }
}
What I am trying to do is to use Automapper to map my Container to my ContaineeDTO. I feel like this should use a resolver, especially for passing Code from the Container to the Containee DTO, but I'm unsure about how to proceed, any help would be appreciated.
CodePudding user response:
You can place this configuration in Startup.cs
:
var config = new MapperConfiguration(
cfg => cfg.CreateMap<Container, ContaineeDTO>()
.ForMember(containeeDto => containeeDto.Value, opt =>
opt.MapFrom(container => container.Containee.Value))
.ForMember(containeeDto => containeeDto.DifferentStr, opt =>
opt.MapFrom(container => container.Containee.DifferentStr))
.ForMember(containeeDto => containeeDto.birthday, opt =>
opt.MapFrom(container => container.Containee.birthday));
Important note: you named properties same in two classes, so there is no necessity to provide their names in mapping definition (as you see, I didn't do it)