Allow mapping of dynamic types using AutoMapper or similar?

AutoMapper 4.2.0 now supports Dynamic/expando/dictionary mapping

With this feature you can map to your expando objects to static types:

dynamic CurUser = _users.GetSingleUser(UserID);   
var config = new MapperConfiguration(cfg => { });
var mapper = config.CreateMapper();

var retUser = mapper.Map<UserModel>(CurUser);

Old versions of AutoMapper do not support this (Massive internally uses ExpandoObject which doesn’t provide which properties it has), and you are right Mapper.DynamicMap is for mapping without creating mapping configuration.

Actually it’s not hard to write yourself a mapper if you just want simple mapping:

public static class DynamicToStatic
{
    public static T ToStatic<T>(object expando)
    {
        var entity = Activator.CreateInstance<T>();

        //ExpandoObject implements dictionary
        var properties = expando as IDictionary<string, object>; 

        if (properties == null)
            return entity;

        foreach (var entry in properties)
        {
            var propertyInfo = entity.GetType().GetProperty(entry.Key);
            if(propertyInfo!=null)
                propertyInfo.SetValue(entity, entry.Value, null);
        }
        return entity;
    }
}

dynamic CurUser = _users.GetSingleUser(UserID);   
var retUser = DynamicToStatic.ToStatic<UserModel>(CurUser);

Leave a Comment