目录
目录
1. Nuget安装AutoMapper
2. 封装方法
3. 简单的示例类型
4. 应用
5. 输出
6. 对象映射其他方式
6.1 反射实现
6.2 序列化实现
6.3 表达式目录树实现
1. Nuget安装AutoMapper
AutoMapper是一个强大的对象映射工具,可以很方便的实现实体和实体之间的转换
2. 封装方法
//使用AutoMapper可以很方便的实现实体和实体之间的转换,它是一个强大的对象映射工具。
///
/// AutoMapper扩展帮助类
///
public static class AutoMapperHelper
{
///
/// 类型映射,默认字段名字一一对应
///
/// 转化之后的实体
/// 要被转化的实体,Entity
/// 可以使用这个扩展方法的类型,任何引用类型
/// 转化之后的实体
public static TDestination MapTo(this TSource source)
where TDestination : class
where TSource : class
{
if (source == null)
{
return default(TDestination);
}
//创建映射关系
var config = new MapperConfiguration(cfg => cfg.CreateMap());
//基于config生成mapper
var mapper = config.CreateMapper();
//执行转换
return mapper.Map(source);
}
///
/// 集合列表类型映射,默认字段名字一一对应
///
/// 转化之后的实体
/// 要被转化的实体,Entity
/// 可以使用这个扩展方法的类型,任何引用类型
/// 转化之后的实体列表
public static IEnumerable MapToList(this IEnumerable source)
where TDestination : class
where TSource : class
{
if (source == null)
{
return new List();
}
var config = new MapperConfiguration(cfg => cfg.CreateMap());
var mapper = config.CreateMapper();
return mapper.Map>(source);
}
}
3. 简单的示例类型
public class ViewModelA
{
public int ID { get; set; }
public string Name { get; set; }
}
public class ViewModelB
{
public int ID { get; set; }
public string Name { get; set; }
}
public class ViewModelC
{
public int Key { get; set; }
public string Tag { get; set; }
public int Age { get; set; }
}
4. 应用
//automapper测试
ViewModelA viewModelA = new ViewModelA
{
ID = 2,
Name = "Kilter"
};
ViewModelB viewModelB= viewModelA.MapTo();
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(viewModelB));
//两个实体的属性名字没有全部对应的 单独处理
MapperConfiguration config = new MapperConfiguration(cfg=>cfg.CreateMap()
.ForMember(d=>d.Key,opt=>opt.MapFrom(s=>s.ID)) //指定属性一一对应
.ForMember(d=>d.Age,opt=>opt.Ignore()) //忽略该字段,不给该字段赋值
.ForMember(d=>d.Tag,opt=>opt.MapFrom(s=>s.ID+"qwer"+s.Name)) //可以随意组合赋值
);
IMapper mapper = config.CreateMapper();
ViewModelC viewModelC = mapper.Map(viewModelA);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(viewModelC));
//列表映射
ViewModelA modelA = new ViewModelA
{
ID = 3,
Name = "taidi"
};
List modelAs = new List() { viewModelA, modelA };
var modelB= modelAs.MapToList();
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(modelB));
5. 输出
- >(source);
}
}
public class ViewModelA
{
public int ID { get; set; }
public string Name { get; set; }
}
public class ViewModelB
{
public int ID { get; set; }
public string Name { get; set; }
}
public class ViewModelC
{
public int Key { get; set; }
public string Tag { get; set; }
public int Age { get; set; }
}
4. 应用
//automapper测试
ViewModelA viewModelA = new ViewModelA
{
ID = 2,
Name = "Kilter"
};
ViewModelB viewModelB= viewModelA.MapTo();
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(viewModelB));
//两个实体的属性名字没有全部对应的 单独处理
MapperConfiguration config = new MapperConfiguration(cfg=>cfg.CreateMap()
.ForMember(d=>d.Key,opt=>opt.MapFrom(s=>s.ID)) //指定属性一一对应
.ForMember(d=>d.Age,opt=>opt.Ignore()) //忽略该字段,不给该字段赋值
.ForMember(d=>d.Tag,opt=>opt.MapFrom(s=>s.ID+"qwer"+s.Name)) //可以随意组合赋值
);
IMapper mapper = config.CreateMapper();
ViewModelC viewModelC = mapper.Map(viewModelA);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(viewModelC));
//列表映射
ViewModelA modelA = new ViewModelA
{
ID = 3,
Name = "taidi"
};
List modelAs = new List() { viewModelA, modelA };
var modelB= modelAs.MapToList();
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(modelB));
5. 输出
6. 对象映射其他方式
6.1 反射实现
public static class ObjectMapperHelper
{
public static TDestination MapToByReflection(this TSource tIn)
{
TDestination tOut = Activator.CreateInstance();
foreach (var itemOut in tOut.GetType().GetProperties())
{
foreach (var itemIn in tIn.GetType().GetProperties())
{
if (itemOut.Name.Equals(itemIn.Name))
{
itemOut.SetValue(tOut, itemIn.GetValue(tIn));
break;
}
}
}
foreach (var itemOut in tOut.GetType().GetFields())
{
foreach (var itemIn in tIn.GetType().GetFields())
{
if (itemOut.Name.Equals(itemIn.Name))
{
itemOut.SetValue(tOut, itemIn.GetValue(tIn));
break;
}
}
}
return tOut;
}
}
6.2 序列化实现
public static class ObjectMapperHelper
{
public static TDestination MapToByJsonserialize(this TSource tIn)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject(Newtonsoft.Json.JsonConvert.SerializeObject(tIn));
}
}
6.3 表达式目录树实现
public static class ExpressionGenericMapperHelper
{
///
/// 表达式目录树实现对象映射 扩展方法
///
/// 要被转化的实体
/// 转化之后的实体
///
///
public static TDestination ExpressionMapTo(this TSource source)
{
//参数表达式
ParameterExpression parameterExpression = Expression.Parameter(typeof(TSource), "P");
//创建绑定列表 绑定用于对新创建对象的成员进行初始化
List memberBindingList = new List();
//把TSource的属性值绑定到TDestination的属性进行初始化
foreach (var item in typeof(TDestination).GetProperties())
{
MemberExpression property = Expression.Property(parameterExpression, typeof(TSource).GetProperty(item.Name));
MemberBinding memberBinding = Expression.Bind(item, property);
memberBindingList.Add(memberBinding);
}
//把TSource的字段值绑定到TDestination的字段进行初始化
foreach (var item in typeof(TDestination).GetFields())
{
MemberExpression field = Expression.Field(parameterExpression, typeof(TSource).GetField(item.Name));
MemberBinding memberBinding = Expression.Bind(item, field);
memberBindingList.Add(memberBinding);
}
//初始化新对象
MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TDestination)), memberBindingList.ToArray());
//创建表达式目录树
Expression> expression = Expression.Lambda>(memberInitExpression, new ParameterExpression[]
{
parameterExpression
});
//从表达式目录树生成委托
Func _func = expression.Compile();
//调用
return _func.Invoke(source);
}
}
public static class ObjectMapperHelper
{
public static TDestination MapToByReflection(this TSource tIn)
{
TDestination tOut = Activator.CreateInstance();
foreach (var itemOut in tOut.GetType().GetProperties())
{
foreach (var itemIn in tIn.GetType().GetProperties())
{
if (itemOut.Name.Equals(itemIn.Name))
{
itemOut.SetValue(tOut, itemIn.GetValue(tIn));
break;
}
}
}
foreach (var itemOut in tOut.GetType().GetFields())
{
foreach (var itemIn in tIn.GetType().GetFields())
{
if (itemOut.Name.Equals(itemIn.Name))
{
itemOut.SetValue(tOut, itemIn.GetValue(tIn));
break;
}
}
}
return tOut;
}
}
6.2 序列化实现
public static class ObjectMapperHelper
{
public static TDestination MapToByJsonserialize(this TSource tIn)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject(Newtonsoft.Json.JsonConvert.SerializeObject(tIn));
}
}
6.3 表达式目录树实现
public static class ExpressionGenericMapperHelper
{
///
/// 表达式目录树实现对象映射 扩展方法
///
/// 要被转化的实体
/// 转化之后的实体
///
///
public static TDestination ExpressionMapTo(this TSource source)
{
//参数表达式
ParameterExpression parameterExpression = Expression.Parameter(typeof(TSource), "P");
//创建绑定列表 绑定用于对新创建对象的成员进行初始化
List memberBindingList = new List();
//把TSource的属性值绑定到TDestination的属性进行初始化
foreach (var item in typeof(TDestination).GetProperties())
{
MemberExpression property = Expression.Property(parameterExpression, typeof(TSource).GetProperty(item.Name));
MemberBinding memberBinding = Expression.Bind(item, property);
memberBindingList.Add(memberBinding);
}
//把TSource的字段值绑定到TDestination的字段进行初始化
foreach (var item in typeof(TDestination).GetFields())
{
MemberExpression field = Expression.Field(parameterExpression, typeof(TSource).GetField(item.Name));
MemberBinding memberBinding = Expression.Bind(item, field);
memberBindingList.Add(memberBinding);
}
//初始化新对象
MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TDestination)), memberBindingList.ToArray());
//创建表达式目录树
Expression> expression = Expression.Lambda>(memberInitExpression, new ParameterExpression[]
{
parameterExpression
});
//从表达式目录树生成委托
Func _func = expression.Compile();
//调用
return _func.Invoke(source);
}
}
public static class ExpressionGenericMapperHelper
{
///
/// 表达式目录树实现对象映射 扩展方法
///
/// 要被转化的实体
/// 转化之后的实体
///
///
public static TDestination ExpressionMapTo(this TSource source)
{
//参数表达式
ParameterExpression parameterExpression = Expression.Parameter(typeof(TSource), "P");
//创建绑定列表 绑定用于对新创建对象的成员进行初始化
List memberBindingList = new List();
//把TSource的属性值绑定到TDestination的属性进行初始化
foreach (var item in typeof(TDestination).GetProperties())
{
MemberExpression property = Expression.Property(parameterExpression, typeof(TSource).GetProperty(item.Name));
MemberBinding memberBinding = Expression.Bind(item, property);
memberBindingList.Add(memberBinding);
}
//把TSource的字段值绑定到TDestination的字段进行初始化
foreach (var item in typeof(TDestination).GetFields())
{
MemberExpression field = Expression.Field(parameterExpression, typeof(TSource).GetField(item.Name));
MemberBinding memberBinding = Expression.Bind(item, field);
memberBindingList.Add(memberBinding);
}
//初始化新对象
MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TDestination)), memberBindingList.ToArray());
//创建表达式目录树
Expression> expression = Expression.Lambda>(memberInitExpression, new ParameterExpression[]
{
parameterExpression
});
//从表达式目录树生成委托
Func _func = expression.Compile();
//调用
return _func.Invoke(source);
}
} 


