Reputation: 4360
I have a model class:
public class Model {
public int Id {get;set;}
public string Name {get;set;}
}
and a view model:
public class ViewModel {
public string Name {get;set;}
}
I want to map List to Dictionary where the key will be Model.Id.
I have started with such configuration:
configuration
.CreateMap<Model, KeyValuePair<int, ViewModel>>()
.ConstructUsing(
x =>
new KeyValuePair<int, ViewModel>(x.Id, _mapper.Map<ViewModel>(x)));
But I don't want to use mapper instance in the configuration. Is there any other way to achieve this? I've seen some answers, where people used x.MapTo(), but that doesn't seem to be available anymore...
Upvotes: 1
Views: 588
Reputation: 4360
The solution provided by @hazevich stopped working after 5.0 update. This is working solution.
You need to create a type converter:
public class ToDictionaryConverter : ITypeConverter<Model, KeyValuePair<int, ViewModel>>
{
public KeyValuePair<int, ViewModel> Convert(Model source, KeyValuePair<int, ViewModel> destination, ResolutionContext context)
{
return new KeyValuePair<int, ViewModel>(source.Id, context.Mapper.Map<ViewModel>(source));
}
}
and then use it in the configuration:
configuration
.CreateMap<Model, KeyValuePair<int, ViewModel>>()
.ConvertUsing<ToDictionaryConverter>();
Upvotes: 0
Reputation: 478
You can use mapper instance from lambda parameter x.Engine.Mapper
Simple as this
configuration
.CreateMap<Model, KeyValuePair<int, ViewModel>>()
.ConstructUsing(context => new KeyValuePair<int, ViewModel>(
((Model)context.SourceValue).Id,
context.Engine.Mapper.Map<ViewModel>(context.SourceValue)));
Upvotes: 1