AutoMapper对象映射工具:主要是将某一个实体转成另一个实体。
1.引用NuGet包;搜索:AutoMapper
2.创建实体类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AutoMapper { public static class AutoMapperExtension { /// <summary> /// 单个对象映射 /// </summary> /// <typeparam name="TSource">源对象</typeparam> /// <typeparam name="TDestination">目标对象</typeparam> /// <param name="source"></param> /// <returns></returns> public static TDestination MapTo<TSource, TDestination>(TSource source) { if (source == null) return default(TDestination); Mapper.Initialize(x => x.CreateMap(typeof(TSource), typeof(TDestination))); return Mapper.Map<TDestination>(source); } /// <summary> /// 集合列表类型映射 /// </summary> /// <typeparam name="TSource">源对象</typeparam> /// <typeparam name="TDestination">目标对象</typeparam> /// <param name="source"></param> /// <returns></returns> public static List<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source) { if (source == null) return default(List<TDestination>); Mapper.Initialize(x => x.CreateMap(typeof(TSource), typeof(TDestination))); return Mapper.Map<List<TDestination>>(source); } } }
3.作为例子。建立两个实体对象
(老会员实体)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AutoMapper { public class UserModel { /// <summary> /// 会员编号 /// </summary> public Int32 UserId { get; set; } /// <summary> /// 会员名称 /// </summary> public String Name { get; set; } } }
新会员实体
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AutoMapper { /// <summary> /// 新会员表 /// </summary> public class UserNewModel { /// <summary> /// 会员编号 /// </summary> public Int32 UserId { get; set; } /// <summary> /// 会员名称 /// </summary> public String Name { get; set; } } }
4.使用方法。在项目过程中。如果需要将两个实体进行转化。使用实例
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AutoMapper { public class Extension { /// <summary> /// 将user转成userNew /// </summary> public static void Model() { var user = new UserModel() { UserId = 1, Name = "王彬" }; var userNew = new UserNewModel(); //将老会员实体转成新会员实体 var u = AutoMapperExtension.MapTo<UserModel,UserNewModel>(user); } public static void ModelList() { List<UserModel> Users = new List<UserModel>(); var user = new UserModel() { UserId = 1, Name = "王彬" }; Users.Add(user); var userNew = new List<UserNewModel>(); //将老会员实体转成新会员实体 var ulist = AutoMapperExtension.MapToList<UserModel, UserNewModel>(Users); } } }
时间: 2024-10-01 03:11:39