Reputation: 933
I have a number of objects that all have a CreatedDt property. Each of these objects needs to be mapped to a matching DTO that has a Created_dt property.
Using AutoMapper, how do I set up a generic configuration to map CreatedDt to Created_dt (and vise versa) without having to do it manually for each map?
Upvotes: 1
Views: 557
Reputation: 5787
There is a lot of ways to achieve this result:
class Program
{
static void Main(string[] args)
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<A, ADto>();
cfg.AddMemberConfiguration()
.AddName<ReplaceName>(_ => _.AddReplace(nameof(A.CreateDate), nameof(ADto.Created_dt)));
});
var mapper = config.CreateMapper();
var a = new A { CreateDate = DateTime.UtcNow, X = "X" };
var aDto = mapper.Map<ADto>(a);
}
}
public class A
{
public DateTime CreateDate { get; set; }
public string X { get; set; }
}
public class ADto
{
public DateTime Created_dt { get; set; }
public string X { get; set; }
}
public class Foo
{
[MapTo("Created_dt")]
public int CreatedDt { get; set; }
}
Upvotes: 1