开发过程中由于定义了多个给数据模型(视图模型、数据库模型),每次都一个一个字段赋值比较耗时,所以做了个自定义一个映射。
因为项目所需要求比较简单所以也没用AutoMapper。
使用到的类
MapAttribute:映射特性,用于解决不同字段名的映射,且优先于字段名
MapHelper:映射特性的操作方法,针对的是映射特性
StringExtend:字符串扩展方法
ObjExtend:对象扩展方法,映射实现在此方法中
类的具体定义
MapAttribute 映射特性
using System;
namespace Common
{
/// <summary>
/// 映射特性
/// AllowMultiple:是否可以为一个程序元素,指定多个所指示特性
/// Inherited:是否特性由派生类和重写成员继承
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field,
AllowMultiple = false,Inherited = false)]
public class MapAttribute : Attribute
{
//=================== construct function ==================
#region construct 属性
/// <summary>
/// 属性
/// </summary>
public MapAttribute(string name)
{
this.m_name = name;
}
#endregion
//=================== private fields ======================
#region fields
private string m_name;
#endregion
//=================== public properties ===================
#region Name 名称
/// <summary>
/// 名称
/// </summary>
public string Name => this.m_name;
#endregion
}
}
MapHelper 映射特性的操作方法
using System;
using System.Collections.Generic;
namespace Common
{
public class MapHelper
{
//================== construct function ===================
#region construct 映射帮助类
/// <summary>
/// 映射帮助类
/// </summary>
public MapHelper()
{
}
#endregion
//==================== public method ======================
#region GetMapAttr 获取Map特性字段
/// <summary>
/// 获取Map特性字段(如果没有则使用字段名)
/// </summary>
/// <returns></returns>
public static Dictionary<string, object> GetMapAttr<T>(T data) where T : class
{
var _res = new Dictionary<string, object>();
if (data == null)
{
return _res;
}
var _type = data.GetType();
var _propArr = _type.GetProperties();//获取所有公共属性
MapAttribute[] attrs;
foreach (var _prop in _propArr)
{
//获取Map特性
attrs = _prop.GetCustomAttributes(typeof(MapAttribute), false) as MapAttribute[];
if (attrs != null && attrs.Length > 0)
{
_res.Add(attrs[0].Name, _prop.GetValue(data));
}
else
{
_res.Add(_prop.Name, _prop.GetValue(data));
}
}
return _res;
}
#endregion
#region SetMapAttrData 设置Map特性对应字段填充数据
/// <summary>
/// 设置Map特性对应字段填充数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="data"></param>
public static void SetMapAttrData<T>(Dictionary<string, object> source, T data)
{
var _type = data