安装方式:使用vs自带的nuget管理工具,搜索AutoMapper ,选择第一个安装到你的项目即可。

我从网上找了一些资料,

参考网址:http://blog.csdn.net/csethcrm/article/details/52934325

下载了个demo,然后自己又写了一遍,我把AutoMapper 的使用分为两种:

1、viewmodel与实体的字段名字是一致的,viewmodel的字段可以与实体中的字段数量不一致。

还有一种情况是:源实体中的字段名字是Getxxx,那么viewmodel中对应的字段可以是xxx,也会自动对应赋值,比如我写的demo中源实体中GetA,viewmodel中的A;

再有一种情况就是实体中的实体赋值,在我写的这个例子中,源实体中包含的实体类字段为Sub,里面包含的字段名字为Age,

那么destmodel中对应的字段名字可以是:SubAge,那么automapper就可以自动为你赋值了,大家看最后的运行结果。

给大家看下我建的源实体:

    public class Source1
{
public string Name { set; get; } public string GetA { set; get; }
public string GetD { set; get; } public string SetB { set; get; } public string c { set; get; } public SubSource1 Sub { set; get; }
} public class SubSource1
{
public string Age { set; get; }
}

还有viewmodel(要转化成为你想要的模型):

    public class Dest1
{
public string Name { set; get; } public string A { set; get; } public string C { set; get; } public string SubAge { set; get; } public string D { set; get; }
}

我封装的扩展方法:

        /// <summary>
/// 类型映射,默认字段名字一一对应
/// </summary>
/// <typeparam name="TDestination">转化之后的model,可以理解为viewmodel</typeparam>
/// <typeparam name="TSource">要被转化的实体,Entity</typeparam>
/// <param name="source">可以使用这个扩展方法的类型,任何引用类型</param>
/// <returns>转化之后的实体</returns>
public static TDestination MapTo<TDestination, TSource>(this TSource source)
where TDestination : class
where TSource : class
{
if (source == null) return default(TDestination);
var config = new MapperConfiguration(cfg => cfg.CreateMap<TSource, TDestination>());
var mapper = config.CreateMapper();
return mapper.Map<TDestination>(source);
}

使用方式:

                var source1 = new Source1
{
Name = "source",
Sub = new SubSource1 { Age = "" },
c = "c",
GetA = "A",
SetB = "B"
}; var destViewModel = source1.MapTo<Source1,Dest1>();

运行结果:

2.viewmodel与实体字段名字没有全部对应,只有几个字段的名字和源实体中的字段名字是一样的,其他的字段是通过实体中的几个字段组合或者是格式或者是类型转化而来的,

使用方法:不能再使用这个扩展方法了,只能自己额外写代码,代码如下:

               var config2 = new MapperConfiguration(
cfg => cfg.CreateMap<SourceUser, DestUser2>()
.ForMember(d => d.DestName, opt => opt.MapFrom(s => s.Name)) //指定字段一一对应
.ForMember(d => d.Birthday, opt => opt.MapFrom(src => src.Birthday.ToString("yy-MM-dd HH:mm")))//指定字段,并转化指定的格式
.ForMember(d => d.Age, opt => opt.Condition(src => src.Age > ))//条件赋值
.ForMember(d => d.A1, opt => opt.Ignore())//忽略该字段,不给该字段赋值
.ForMember(d => d.A1, opt => opt.NullSubstitute("Default Value"))//如果源字段值为空,则赋值为 Default Value
.ForMember(d => d.A1, opt => opt.MapFrom(src => src.Name + src.Age * + src.Birthday.ToString("d"))));//可以自己随意组合赋值
var mapper2 = config2.CreateMapper();

注释中都包含了平时常用的几种情况,其他的我就没有再写。

下面再给大家把list转化的扩展方法代码贴上:

        /// <summary>
/// 集合列表类型映射,默认字段名字一一对应
/// </summary>
/// <typeparam name="TDestination">转化之后的model,可以理解为viewmodel</typeparam>
/// <typeparam name="TSource">要被转化的实体,Entity</typeparam>
/// <param name="source">可以使用这个扩展方法的类型,任何引用类型</param>
/// <returns>转化之后的实体列表</returns>
public static IEnumerable<TDestination> MapToList<TSource,TDestination>(this IEnumerable<TSource> source)
where TDestination : class
where TSource : class
{
if (source == null) return new List<TDestination>();
var config = new MapperConfiguration(cfg => cfg.CreateMap<TSource, TDestination>());
var mapper = config.CreateMapper();
return mapper.Map<List<TDestination>>(source);
}

同样的使用方式:

                var source1 = new Source1
{
Name = "source",
Sub = new SubSource1 { Age = "" },
c = "c",
GetA = "A",
SetB = "B"
};
          var source3 = new Source1
{
Name = "source3",
Sub = new SubSource1 { Age = "" },
c = "c3",
GetA = "A3",
SetB = "B3"
};
var sourceList = new List<Source1> { source1, source3 };
var destViewModelList = sourceList.MapToList<Source1,Dest1>();

运行结果:

以上就是我个人所得,如有错误,欢迎大家指正。

//2017.12.4 修改:destination和source写反了,导致我的总结有些错误,现在纠正一下:错误结论已经红色标注,中间的截图也换成正确的了,工具类方法也已经修正。

c# AutoMapper 使用方式的更多相关文章

  1. c# AutoMapper 使用方式和再封装

    安装方式:使用vs自带的nuget管理工具,搜索AutoMapper ,选择第一个安装到你的项目即可. 我从网上找了一些资料, 参考网址:http://blog.csdn.net/csethcrm/a ...

  2. Asp.NetCore之AutoMapper基础篇

    应用场景 现在由于前后端技术的分离,后端程序员在使用ORM框架开发后台API接口的时候,往往会将数据库的"数据模型"直接提供给前端.而大多数时候,可能这些数据并不能够满足前端展示的 ...

  3. AutoMapper实现对象转换的几种方式

    namespace ConsoleApplication1 { class Program { static void Main(string[] args) { //1.普通转换 Name name ...

  4. 【AutoMapper官方文档】DTO与Domin Model相互转换(上)

    写在前面 AutoMapper目录: [AutoMapper官方文档]DTO与Domin Model相互转换(上) [AutoMapper官方文档]DTO与Domin Model相互转换(中) [Au ...

  5. AutoMapper使用中的问题

    指定值只会执行一次 public class MomanBaseProfile : Profile { public MomanBaseProfile() { CreateMap<Request ...

  6. 【AutoMapper官方文档】DTO与Domin Model相互转换(中)

    写在前面 AutoMapper目录: [AutoMapper官方文档]DTO与Domin Model相互转换(上) [AutoMapper官方文档]DTO与Domin Model相互转换(中) [Au ...

  7. 【AutoMapper官方文档】DTO与Domin Model相互转换(下)

    写在前面 AutoMapper目录: [AutoMapper官方文档]DTO与Domin Model相互转换(上) [AutoMapper官方文档]DTO与Domin Model相互转换(中) [Au ...

  8. 【道德经】漫谈实体、对象、DTO及AutoMapper的使用

    写在前面 实体和值对象 实体和对象 故常无欲以观其妙,常有欲以观其徼 初始实体和演化实体 代码中的DTO AutoMapper实体转换 后记 实体(Entity).对象(Object).DTO(Dat ...

  9. AutoMapper(四)

    返回总目录 自定义值解析 虽然AutoMapper覆盖了相当一部分目标成员的映射场景,但是还有 1-5%的目标值需要解析处理一下.很多时候,自定义的值解析是可以放在领域层的领域逻辑.然而,如果该逻辑只 ...

随机推荐

  1. apache+php+mysql运行环境

    建议Apache2.4+php5.6+mysql5.5+phpmyadmin4.4.4 参考: http://jingyan.baidu.com/article/fcb5aff797ec41edaa4 ...

  2. [原创]浅谈JAVA在ACM中的应用

    由于java里面有一些东西比c/c++方便(尤其是大数据高精度问题,备受广大ACMer欢迎),所以就可以灵活运用这三种来实现编程,下面是我自己在各种大牛那里总结了一些,同时加上自己平时遇到的一些jav ...

  3. abapGit简介与教程

    你是ABAP开发者?你用abapGit吗? 看到这个问题,读者也许会想,什么是abapGit?就让我们从这个问题开始.简单地说,abapGit是一个以ABAP写成为ABAP服务的Git客户端. 有的读 ...

  4. EF6与Mysql疑难问题记录

    这几天公司架构调整,新的迭代后端使用了ABP框架与CodeFirst模式,执行过程中遇到了一个非必现很难定位的问题,特此记录. 现象 在程序访问MySql数据库时报了异常 System.Invalid ...

  5. Spring中的注入方式

    在Spring配置文件中使用XML文件进行配置,实际上是让Spring执行了相应的代码,例如: 使用<bean>元素,实际上是让Spring执行无参或有参构造器 使用<propert ...

  6. Can you solve this equation?

    Can you solve this equation? Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Jav ...

  7. 使用Apache Commons Email 发生邮件

    Apache Commons Email的Maven依赖 <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-e ...

  8. web前端免费资源集

    web前端免费资源集 https://github.com/vhf/free-programming-books/blob/master/free-programming-books-zh.md

  9. 从一个实例谈谈postgresql索引锁

    最近客户在使用我司开发的数据库时,报告了如下问题(也不能算是问题,就是疑惑吧),环境如下: OS : Red Hat Enterprise Linux Server release 6.7 (Sant ...

  10. Spring Security Ajax 被拦截

    背景是项目中使用Spring Security 进行安全控制 再使用Ajax的时候会报 403(ajax get  方式是没问题的 post 的时候会报) Spring Security 原本是 防止 ...