Home > database >  AutoMapper - Map model to Dictionary
AutoMapper - Map model to Dictionary

Time:11-17

I am trying to map a DTO to Dictionary<string, object> using AutoMapper:

public class SetEmr
{
    public string Name { get; set; }
    public int Repeat { get; set; }
    public int RestTime { get; set; }
    public int Order { get; set; }
}

I'm trying to do something like this:

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

It doesn't work.

"Custom configuration for members is only supported for top-level individual members on a type."

Are there any other ways to implement such a mapping?

CodePudding user response:

Solution 1

Instead, you should use .ConvertUsing() for the type conversion.

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

Solution 2

Credit to @Lucian's comment, AutoMapper does support mapping from class instance to dynamic/ExpandoObject. Hence, you can directly perform the mapping to Dictionary<string, object> without specifying the mapping configuration/rule.

Demo @ .NET Fiddle

  • Related