Allow mapping of dynamic types using AutoMapper or similar?

前端 未结 4 1127
攒了一身酷
攒了一身酷 2020-12-02 05:46

I\'ve started to use https://github.com/robconery/massive for a project, I wonder if there is any mapping tool that allows support for Dynamic to static type mapping?

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 06:24

    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(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(object expando)
        {
            var entity = Activator.CreateInstance();
    
            //ExpandoObject implements dictionary
            var properties = expando as IDictionary; 
    
            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(CurUser);
    

提交回复
热议问题