一、原文地址:
大佬的链接:https://www.cnblogs.com/fred-bao/p/5700776.html
二、前言:
通常在一个应用程序中,我们开发人员会在两个不同的类型对象之间传输数据,通常我们会用DTOs(数据传输对象),View Models(视图模型),或者直接是一些从一个service或者Web API的一些请求或应答对象。一个常见的需要使用数据传输对象的情况是,我们想把属于一个对象的某些属性值赋值给另一个对象的某些属性值,但是问题是,这个两个对象可能并不是完全匹配的,比如,两者之间的属性类型,名称等等,是不一样的,或者我们只是想把一个对象的一部分属性值赋值给另一个对象。
三、示例
首先,让我们来看下之前的处理方式,我们通过以下这个例子来直观感受这种方式,我们创建了以下三个类:
1 public class Author 2 { 3 public string Name { get; set; } 4 } 5 public class Book 6 { 7 public string Title { get; set; } 8 public Author Author { get; set; } 9 } 10 public class BookViewModel 11 { 12 public string Title { get; set; } 13 public string Author { get; set; } 14 }
为了创建Book对象实例的一个View Model对象实例-BookViewModel对象实例,我们需要写如下代码:
1 BookViewModel model = new BookViewModel 2 { 3 Title = book.Title, 4 Author = book.Author.Name 5 }
上面的例子相当的直观了,但是问题也随之而来了,我们可以看到在上面的代码中,如果一旦在Book对象里添加了一个额外的字段,而后想在前台页面输出这个字段,那么就需要去在项目里找到每一处有这样转换字段的地方,这是非常繁琐的。另外,BookViewModel.Author是一个string类型的字段,但是Book.Author属性却是Author对象类型的,我们用的解决方法是通过Book.Auther对象来取得Author的Name属性值,然后再赋值给BookViewModel的Author属性,这样看起行的通,但是想一想,如果打算在以后的开发中把Name拆分成两个-FisrtName和LastName,那么,呵呵,我们得去把原来的ViewModel对象也拆分成对应的两个字段,然后在项目中找到所有的转换,然后替换。
那么有什么办法或者工具来帮助我们能够避免这样的情况发生呢?AutoMapper正是符合要求的一款插件。
四、使用AutoMapper进行映射
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Conautomapper 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 Exmple_One(); 14 Console.ReadKey(); 15 } 16 17 static void Exmple_One() 18 { 19 AutoMapper.Mapper.CreateMap<Book, BookViewModel>() 20 .ForMember(t => t.Author, s => s.MapFrom(u => u.Author.Name)); 21 22 Book book = new Book() 23 { 24 Title = "Leesin", 25 Author = new Author() 26 { 27 Name = "Lee" 28 } 29 }; 30 31 var model = AutoMapper.Mapper.Map<BookViewModel>(book); 32 } 33 } 34 #region Exmple_One 35 public class Author 36 { 37 public string Name { get; set; } 38 } 39 public class Book 40 { 41 public string Title { get; set; } 42 public Author Author { get; set; } 43 } 44 public class BookViewModel 45 { 46 public string Title { get; set; } 47 public string Author { get; set; } 48 } 49 #endregion 50 }
五、总结
仅是测试编写,未在项目中实际运用,还有更多未知的问题和操作。