博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
AutoMapper的简单使用
阅读量:6704 次
发布时间:2019-06-25

本文共 6357 字,大约阅读时间需要 21 分钟。

1. 第一种方法,推荐!

添加一个功能类

using AutoMapper;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace AutoMapperTest2{    public static class AutoMapperConfig    {        public static IMapper Mapper = new Mapper(RegisterMappings());        public static MapperConfiguration RegisterMappings()        {            return new MapperConfiguration(cfg =>            {                cfg.CreateMissingTypeMaps = true;                cfg.AllowNullDestinationValues = false;                cfg.ForAllPropertyMaps(IsToRepeatedField, (propertyMap, opts) => opts.UseDestinationValue());                cfg.ForAllPropertyMaps(IsToMapFieldField, (propertyMap, opts) => opts.UseDestinationValue());                cfg.AddProfile
(); }); bool IsToRepeatedField(PropertyMap pm) { if (pm.DestinationPropertyType.IsConstructedGenericType) { var destGenericBase = pm.DestinationPropertyType.GetGenericTypeDefinition(); return false;// destGenericBase == typeof(RepeatedField<>); } return false; } bool IsToMapFieldField(PropertyMap pm) { if (pm.DestinationPropertyType.IsConstructedGenericType) { var destGenericBase = pm.DestinationPropertyType.GetGenericTypeDefinition(); return false;// destGenericBase == typeof(MapField<,>); } return false; } } } public class OutputModels : Profile { public OutputModels() { } }}

使用

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace AutoMapperTest2{    class Program    {        static void Main(string[] args)        {            var src = new source() {                name = "jeff",                age  = 1,                strList = new List
() { "1", "2", "3"}, classList = new List
() { new aaa(){a1="a1", a2=1}, new aaa(){a1="a2", a2=2}, new aaa(){a1="a3", a2=3}, } }; var tgt = AutoMapperConfig.Mapper.Map
(src); if (tgt != null) Console.WriteLine($"name = {tgt.name}"); } } public class source { public string name { get; set; } public int age { get; set; } public List
strList { get; set; } public List
classList { get; set; } } public class target { public string name { get; set; } public int age { get; set; } public List
strList { get; set; } public List
classList { get; set; } } public class aaa { public string a1 { get; set; } public int a2 { get; set; } }}

 

 

2. 第二种方法:

添加功能类

using AutoMapper;using System;using System.Collections.Generic;using System.Linq;using System.Web; namespace TCG.DataCollection.Webservice{    public sealed class Mapper    {        private static readonly Mapper instance = new Mapper();        private Mapper()        {            this.Init();        }        public void Init()        {            AutoMapper.Mapper.Initialize(cfg =>            {                departmentMapping(cfg);                this.employeeMapping(cfg);this.defaultMapping
(cfg); this.defaultMapping
(cfg); this.vestingMapping(cfg); }); } public static Dest Map
(Src src) { if (instance != null) return AutoMapper.Mapper.Map
(src); else throw new Exception("Automapper not initialized."); // TODO: 错误信息需集中定义。 } ///
/// 提供默认的类型映射,双向映射,依据属性名称 /// ///
///
///
private void defaultMapping
(IMapperConfigurationExpression cfg) { cfg.CreateMap
(); cfg.CreateMap
(); } private void departmentMapping(IMapperConfigurationExpression cfg) { cfg.CreateMap
() .ForMember(dest => dest.ParentDepartmentCode, options => options.MapFrom(src => string.IsNullOrWhiteSpace(src.ParentDepartmentCode) ? src.DepartmentCode : src.ParentDepartmentCode)); cfg.CreateMap
() .ForMember(dest => dest.ParentDepartmentCode, options => options.MapFrom(src => src.ParentDepartmentCode)); } private void vestingMapping(IMapperConfigurationExpression cfg) { cfg.CreateMap
() .ForMember(dest => dest.VestingDate, options => options.ResolveUsing
(src => this.convertDate(src.VestingDate).GetValueOrDefault())); } private void grantMapping(IMapperConfigurationExpression cfg) { cfg.CreateMap
() .ForMember(dest => dest.GrantDate, options => options.ResolveUsing
(src => { return this.convertDate(src.GrantDate).GetValueOrDefault(); })) .ForMember(dest => dest.GrantType, options => options.ResolveUsing
(src => this.convertGrantType(src.GrantType))) .ForMember(dest => dest.IsPerformanceBased, options => options.ResolveUsing
(src => string.Equals(src.IsPerformanceBased, "Y", StringComparison.OrdinalIgnoreCase))); } private void reinstatementMapping(IMapperConfigurationExpression cfg) { cfg.CreateMap
() .ForMember(dest => dest.ReinstatementDate, options => options.ResolveUsing
(src => this.convertDate(src.ReinstatementDate).GetValueOrDefault())) .ForMember(dest => dest.Type, options => options.UseValue
(ReinstatementType.R)); } private void employeeMapping(IMapperConfigurationExpression cfg) { cfg.CreateMap
() .ForMember(dest => dest.SAFEforSubsequentSalse, options => options.ResolveUsing
(src => string.Equals(src.SAFEforSubsequentSalse, "Y", StringComparison.OrdinalIgnoreCase) ? "1" : string.Empty)); } private DateTime? convertDate(string date) { if (string.IsNullOrEmpty(date)) return null; var year = int.Parse(date.Substring(0, 4)); var month = int.Parse(date.Substring(4, 2)); var day = int.Parse(date.Substring(6, 2)); return new DateTime(year, month, day); } }}

使用时

var model = Mapper.Map
(data);

 

转载于:https://www.cnblogs.com/itjeff/p/10175674.html

你可能感兴趣的文章
iOS 5 编程(2)-开关(UISwitch)、分段控件(UISegmentedControl)和Web视图(UIWebView)控件的使用...
查看>>
GNU make manual 翻译( 一百六十)
查看>>
POJ 2296 Map Labeler(二分+2SAT可行性判断)
查看>>
Entity Framework练习题
查看>>
SQL语句中用Parameters有什么好处
查看>>
SQL中的连接
查看>>
前沿设计推荐-使用jquery打造动感的浮动web界面
查看>>
mfc 类的定义
查看>>
FreeSWITCH 添加中文语音包
查看>>
Delegate如何进行类型转换?
查看>>
销售的最高境界竟然是聊天
查看>>
【原创】解决jquery在ie中不能解析字符串类型xml结构的xml字符串的问题
查看>>
高速排序算法
查看>>
MySql 触发器同步备份数据表记录
查看>>
Flex强制类型转换错误
查看>>
oracle中LAG()和LEAD()等分析统计函数的使用方法(统计月增长率)
查看>>
二分查找
查看>>
【进阶修炼】——改善C#程序质量(1)
查看>>
Ansible@一个高效的配置管理工具--Ansible configure management--翻译(八)
查看>>
Redis多机功能之Sentinel
查看>>