我有许多对象都具有CreatedDt属性。每个对象都需要映射到具有Created_dt属性的匹配DTO。
使用AutoMapper,如何设置通用配置以将CreatedDt映射到Created_dt(反之亦然),而无需为每个地图手动执行此操作?
答案 0 :(得分:1)
有很多方法可以达到这个结果:
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; }
}