.Net Core Api可复用项目架构——Mapper(五)

现在已经有了用于数据库交互的实体模型,以及用于数据传输的API模型,还有一个封装好的仓储接口。那么下一步就可以开始进行数据操作了,从仓储接口操作的数据,是实体模型数据,要转变成视图模型传输给视图,而从视图获取到的数据,是API模型,则需要转换成实体模型后才能进行持久化操作。所以我们需要一个映射器,用于进行两种模型之间的自动转换。

在项目中,我使用过三种映射器:

  1. 利用反射进行映射的泛型映射方法。
  2. 将AutoMapper进行封装后的泛型映射接口。
  3. Lambda表达式进行映射。

如果是构建一个简单的项目,我会倾向于使用第一种,不用安装包而且轻量。
代码:

public static class Mapper
{
    public static TEntityVM MapperToApiEntity<Tid, TEntity, TEntityVM>(TEntity source)
        where TEntity : class, IData<Tid>, new()
        where TEntityVM : class, IData<Tid>, new()
    {
        TEntityVM target = new TEntityVM();
        PropertyInfo[] propertyInfosTarget = typeof(TEntityVM).GetProperties();
        PropertyInfo[] propertyInfosSource = typeof(TEntity).GetProperties();

        foreach (var targetProperty in propertyInfosTarget)
        {
            foreach (var propertyInfo in propertyInfosSource)
            {
                //若为原生类型
                if (!propertyInfo.PropertyType.FullName.Contains("HR") || propertyInfo.PropertyType.IsEnum)
                {
                    if (propertyInfo.Name == targetProperty.Name)
                    {
                        targetProperty.SetValue(target, propertyInfo.GetValue(source));
                        break;
                    }
                }
                //若为自定义类型
                else
                {
                    if(propertyInfo.GetValue(source) == null)
                    {
                        continue;
                    }
                    PropertyInfo[] properties = propertyInfo.PropertyType.GetProperties();
                    foreach (var item in properties)
                    {
                        if(target.GetType().GetProperty(propertyInfo.Name + item.Name) != null)
                        {
                            target.GetType().GetProperty(propertyInfo.Name + item.Name).SetValue(target, item.GetValue((IData<Guid>)propertyInfo.GetValue(source)).ToString());
                        }
                    }
                }
            }
        }
        return target;
    }
    public static List<TEntityVM> MapperToApiEntity<Tid, TEntity, TEntityVM>(IEnumerable<TEntity> sources)
        where TEntity : class, IData<Tid>, new()
        where TEntityVM : class, IData<Tid>, new()
    {
        List<TEntityVM> entityVMs = new List<TEntityVM>();
        if (sources != null)
        {
            foreach (var item in sources)
            {
                entityVMs.Add(MapperToApiEntity<Tid, TEntity, TEntityVM>(item));
            }
        }
        return entityVMs;
    }

    public static List<TEntity> MapperToEntity<Tid, TEntity, TEntityVM>(IEnumerable<TEntityVM> sources)
        where TEntity : class, IData<Tid>, new()
        where TEntityVM : class, IData<Tid>, new()
    {
        List<TEntity> entityVMs = new List<TEntity>();
        if (sources != null)
        {
            foreach (var item in sources)
            {
                entityVMs.Add(MapperToEntity<Tid, TEntity, TEntityVM>(item));
            }
        }
        return entityVMs;
    }

    public static TEntity MapperToEntity<Tid, TEntity, TEntityVM>(TEntityVM source)
        where TEntityVM : class, IData<Tid>, new()
        where TEntity : class, IData<Tid>, new()
    {
        TEntity target = new TEntity();
        PropertyInfo[] propertyInfosTarget = typeof(TEntity).GetProperties();
        PropertyInfo[] propertyInfosSource = typeof(TEntityVM).GetProperties();

        foreach (var propertyInfo in propertyInfosSource)
        {
            foreach (var targetProperty in propertyInfosTarget)
            {
                //若为原生类型
                if (!targetProperty.PropertyType.FullName.Contains("HR") || targetProperty.PropertyType.IsEnum)
                {
                    if (propertyInfo.Name == targetProperty.Name)
                    {
                        targetProperty.SetValue(target, propertyInfo.GetValue(source));
                    }
                }
                //若为自定义类型
                else
                {
                    var tempId =  source.GetType().GetProperty(targetProperty.Name + "Id").GetValue(source).ToString();
                    Guid PropertyId = Guid.Parse(tempId);
                    var PropertyName = source.GetType().GetProperty(targetProperty.Name + "Name");
                    var obj = System.Activator.CreateInstance(targetProperty.PropertyType);
                    obj.GetType().GetProperty("Id").SetValue(obj, PropertyId);
                    if(PropertyName != null)
                    {
                        obj.GetType().GetProperty("Name").SetValue(obj, PropertyName.GetValue(source) == null ? null : PropertyName.GetValue(source).ToString());
                    }
                    target.GetType().GetProperty(targetProperty.Name).SetValue(target, obj);
                }
            }
        }
        return target;
    }
}

但是反射的操作虽然简单,其实是非常耗时的,当数据量小的时候不影响,数据量大,且要求响应快的时候,就会变得不适用。

做过一个测试,使用反射映射一千条数据,花费了3347.3778毫秒,而使用Lambda映射配合缓存表达式只用了0.1538毫秒,当然数据不一定准确,也可能是因为我做的反射映射有问题,大家看个乐子

在这三种里面,Lambda表达式映射是最快且最接近赋值形式映射的,由于赶工的时候写的比较乱,所以下面就只贴其中一部分核心代码,后面如果有时间会具体整理再发出来。

    /// <summary>
    /// 生成映射成视图模型的Lambda表达式
    /// </summary>
    /// <returns></returns>
    private Func<TEntity, TEntityVM> GetMapToEntityVMFunc()
    {
        ParameterExpression parameterExpression = Expression.Parameter(typeof(TEntity), "p");
        // 一组用于映射的模型绑定表达式
        List<MemberBinding> memberBindingList = new List<MemberBinding>();
        foreach (var item in typeof(TEntityVM).GetProperties())
        {
            if (!item.CanWrite)
                continue;
            if (typeof(TEntity).GetProperty(item.Name) == null)
            {
                if (item.Name.Contains("Id"))
                {
                    var tempProperty = typeof(TEntity).GetProperty(item.Name[0..^2]);
                    if (tempProperty != null)
                    {
                        MemberExpression idProperty = Expression.Property(Expression.Property(parameterExpression, tempProperty), "Id");
                        if (item.PropertyType == typeof(string))
                        {
                            MethodInfo methodInfo = idProperty.Type.GetMethod("ToString", new Type[] { });
                            var resultExpression = Expression.Call(idProperty, methodInfo);
                            MemberBinding memberBindingResult = Expression.Bind(item, resultExpression);
                            memberBindingList.Add(memberBindingResult);
                        }
                        else
                        {
                            MemberBinding memberBindingResult = Expression.Bind(item, idProperty);
                            memberBindingList.Add(memberBindingResult);
                        }

                    }
                    else
                        continue;
                }
                else if (item.Name.Contains("Name"))
                {
                    var tempProperty = typeof(TEntity).GetProperty(item.Name[0..^4]);
                    if (tempProperty != null && !tempProperty.PropertyType.IsEnum)
                    {
                        MemberExpression nameProperty = Expression.Property(Expression.Property(parameterExpression, tempProperty), "Name");
                        MemberBinding memberBindingResult = Expression.Bind(item, nameProperty);
                        memberBindingList.Add(memberBindingResult);
                    }
                    else
                        continue;
                }
                else if (item.PropertyType == typeof(string))
                {
                    MemberBinding memberString = Expression.Bind(item, Expression.Constant(""));
                    memberBindingList.Add(memberString);
                }
                continue;
            }
            MemberExpression property = Expression.Property(parameterExpression, typeof(TEntity).GetProperty(item.Name));
            MemberBinding memberBinding = Expression.Bind(item, property);
            memberBindingList.Add(memberBinding);
        }
        MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TEntityVM)), memberBindingList.ToArray());
        Expression<Func<TEntity, TEntityVM>> lambda = Expression.Lambda<Func<TEntity, TEntityVM>>(memberInitExpression, new ParameterExpression[] { parameterExpression });

        return lambda.Compile();
    }

有了映射器,我们就可以开始考虑怎么给用户Show出我们的数据了。

更多文章请关注《万象专栏》