映射列表<Model>到字典<int, ViewModel>

Mapping List<Model> to Dictionary<int, ViewModel>

我有一个模型class:

public class Model {
    public int Id {get;set;}
    public string Name {get;set;}
}

和视图模型:

public class ViewModel {
    public string Name {get;set;}
}

我想将列表映射到键为 Model.Id 的字典。

我已经开始使用这样的配置:

configuration
    .CreateMap<Model, KeyValuePair<int, ViewModel>>()
    .ConstructUsing(
        x =>
            new KeyValuePair<int, ViewModel>(x.Id, _mapper.Map<ViewModel>(x)));

但我不想在配置中使用映射器实例。还有其他方法可以实现这一目标吗?我看到了一些答案,人们在其中使用 x.MapTo(),但似乎不再可用...

您可以使用来自 lambda 参数的映射器实例 x.Engine.Mapper

就这么简单

configuration
    .CreateMap<Model, KeyValuePair<int, ViewModel>>()
    .ConstructUsing(context => new KeyValuePair<int, ViewModel>(
        ((Model)context.SourceValue).Id,
        context.Engine.Mapper.Map<ViewModel>(context.SourceValue)));

@hazevich 提供的解决方案在 5.0 更新后停止工作。这是可行的解决方案。


您需要创建一个类型转换器:

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));
    }
}

然后在配置中使用它:

configuration
    .CreateMap<Model, KeyValuePair<int, ViewModel>>()
    .ConvertUsing<ToDictionaryConverter>();