I am using static class for mapping my entities. But if I use the following code, it is not working for converting lists and nested entities;
public static class MapperUtil<TSource, TDestination>
{
private static readonly Mapper _mapper = new Mapper(new MapperConfiguration(
cfg =>
{
cfg.CreateMap<TDestination,TSource>().ReverseMap();
}));
public static TDestination Map(TSource source)
{
return _mapper.Map<TSource,TDestination>(source);
}
}
But if I use the following code it works well.
var mapper = new Mapper(new MapperConfiguration(cfg =>
{
cfg.CreateMap<List<User>, List<UserDto>>().ReverseMap();
}));
List<UserDto> userDto = mapper.Map<List<User>,List<UserDto>> (users);
Can anyone help me? (I am newbie). And is it good idea using static class for mapping? What is your solution for mapping as static class?
CodePudding user response:
You should remove List
in CreateMap
method and create map for your types:
var mapper = new Mapper(new MapperConfiguration(cfg =>
{
cfg.CreateMap<User, UserDto>().ReverseMap();
}));
Finally:
List<UserDto> userDto = mapper.Map<List<UserDto>>(users);
CodePudding user response:
if you are using generic type for mapping, try below code
public class Source<T> {
public T Value { get; set; }
}
public class Destination<T> {
public T Value { get; set; }
}
// Create the mapping
var configuration = new MapperConfiguration(cfg => cfg.CreateMap(typeof(Source<>), typeof(Destination<>)));