Using AutoMapper to dynamically map objects including arrays

核能气质少年 提交于 2019-12-12 18:25:12

问题


I'm trying to build a way of mapping from one type to another, knwoing they will (should) have the same structure. Related Question.

For ease of the fiddly bits, I'm using AutoMapper from Codeplex, with the following function:

private static List<Type> seenTypes = new List<Type>();

private static void MapDataObjects(Type a, Type b)
{
    AutoMapper.Mapper.CreateMap(a, b);

    PropertyInfo[] aProps = a.GetProperties();
    PropertyInfo[] bProps = b.GetProperties();
    foreach (PropertyInfo aProp in aProps)
    {
        if (aProp.PropertyType.Namespace.StartsWith("System") 
             || seenTypes.Contains(aProp.PropertyType))
            continue;

        foreach (PropertyInfo bProp in bProps)
        {
            if (aProp.Name == bProp.Name)
            {
                MapDataObjects(aProp.PropertyType, bProp.PropertyType);
                seenTypes.Add(aProp.PropertyType);
                break;
            }
        }
    }
 }

Which appears to work fine when stepping through the code, however calling my Map function gives the following error:

AutoMapper.AutoMapperMappingException: 
     Trying to map TDXDataTypes.ClientActivity[] to ClientActivity[].
Using mapping configuration for TDXDataTypes.ClientActivity[] to ClientActivity[]
Destination property: Activities
Exception of type 'AutoMapper.AutoMapperMappingException' was thrown. 
    ---> System.ArgumentException: 
         Type 'ClientActivity[]' does not have a default constructor

回答1:


Found the solution (should have tried harder before asking the question):

 if (aProp.Name == bProp.Name)
    {
        if (aProp.PropertyType.IsArray)
        {
            MapDataObjects(aProp.PropertyType.GetElementType(), bProp.PropertyType.GetElementType());
            seenTypes.Add(aProp.PropertyType.GetElementType());
            break;
        }
        else
        {
            MapDataObjects(aProp.PropertyType, bProp.PropertyType);
            seenTypes.Add(aProp.PropertyType);
            break;
        }
    }


来源:https://stackoverflow.com/questions/2646578/using-automapper-to-dynamically-map-objects-including-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!