AutoMapper - 将模型映射到字典

Mic*_*nko 0 c# automapper

我正在尝试使用 AutoMapper 映射 DTO Dictionary<string, object>

public class SetEmr
{
    public string Name { get; set; }
    public int Repeat { get; set; }
    public int RestTime { get; set; }
    public int Order { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试做这样的事情:

CreateMap<SetEmr, Dictionary<string, object>>()
    .ForMember(dest => dest, opt => opt.MapFrom((src, dst, _, context) =>
    {
        return new Dictionary<string, object>
        {
            { "Name", src.Name },
            { "Repeat", src.Repeat},
            { "Order", src.Order}
        };
    }));
Run Code Online (Sandbox Code Playgroud)

这不起作用。

“只有类型上的顶级个人成员才支持成员的自定义配置。”

还有其他方法可以实现这样的映射吗?

Yon*_*hun 5

解决方案1

相反,您应该使用.ConvertUsing()类型转换

CreateMap<SetEmr, Dictionary<string, object>>()
    .ConvertUsing((src, dst) =>
    {
        return new Dictionary<string, object>
        {
            { "Name", src.Name },
            { "Repeat", src.Repeat},
            { "Order", src.Order}
        };
    });
Run Code Online (Sandbox Code Playgroud)

解决方案2

感谢@Lucian的评论,AutoMapper确实支持从类实例到dynamic/ExpandoObject的映射。因此,您可以直接执行映射,而Dictionary<string, object>无需指定映射配置/规则。

演示@.NET Fiddle