我正在使用AutoMapper dll。 尝试编写一种映射过程的方法。
public ServiceResult<LoginModel> Login(LoginModel model)
{
//-----from here
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<LoginModel, User>();
});
IMapper mapper = config.CreateMapper();
var user = new User();
var dest = mapper.Map<LoginModel, User>(model);
//------ to here
return new ServiceResult<LoginModel>(model);
}
因此,我需要将LoginModel,User和Model设置为动态。 该方法应该简单地如下所示(仅举例来说,我找不到一种方法),
public object Map(Type source, Type destination, object model)
{
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<source, destination>();
});
IMapper mapper = config.CreateMapper();
var user = new User(); (Model of [destination])
var dest = mapper.Map<source, destination>(model);
//map data from model to dest
return new ServiceResult<LoginModel>(model);
}
答案 0 :(得分:-1)
您可以将Map方法更改为通用方法:
public object Map<TSource, TDestination>(object model)
{
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<TSource, TDestination>();
});
IMapper mapper = config.CreateMapper();
var user = new User();
var dest = mapper.Map<TSource, TDestination>(model);
//map data from model to dest
return new ServiceResult<LoginModel>(model);
}