将List <model>映射到Dictionary <int,viewmodel =“”>

时间:2016-06-29 11:12:30

标签: c# automapper

我有一个模型类:

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

和视图模型:

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

我想将List映射到Dictionary,其中键是Model.Id。

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

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

但我不想在配置中使用mapper实例。有没有其他方法来实现这一目标?我已经看到了一些答案,人们使用x.MapTo(),但这似乎不再可用......

2 个答案:

答案 0 :(得分:1)

您可以使用lambda参数x.Engine.Mapper

中的mapper实例

这很简单

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

答案 1 :(得分:0)

@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>();
相关问题