MVC中使用AutoMapper

参考博文

https://www.cnblogs.com/fred-bao/p/5700776.html

前言

通常在一个应用程序中,我们开发人员会在两个不同的类型对象之间传输数据,

通常我们会用DTOs(数据传输对象),View Models(视图模型),或者直接是一些从一个service或者Web API的一些请求或应答对象。

一个常见的需要使用数据传输对象的情况是,我们想把属于一个对象的某些属性值赋值给另一个对象的某些属性值,

但是问题是,这个两个对象可能并不是完全匹配的,比如,两者之间的属性类型,名称等等,是不一样的,或者我们只是想把一个对象的一部分属性值赋值给另一个对象。

示例

首先,让我们来看下之前的处理方式,我们通过以下这个例子来直观感受这种方式,我们创建了以下三个类

public class Author
{
    public string Name { get; set; }
}
public class Book
{
    public string Title { get; set; }
    public Author Author { get; set; }
}
public class BookViewModel
{
    public string Title { get; set; }
    public string Author { get; set; }
}

为了创建Book对象实例的一个View Model对象实例-BookViewModel对象实例,我们需要写如下代码

BookViewModel model = new BookViewModel
{
    Title = book.Title,
    Author = book.Author.Name
}

上面的例子相当的直观了,

但是问题也随之而来了,我们可以看到在上面的代码中,

如果一旦在Book对象里添加了一个额外的字段,而后想在前台页面输出这个字段,

那么就需要去在项目里找到每一处有这样转换字段的地方,这是非常繁琐的。

另外,BookViewModel.Author是一个string类型的字段,但是Book.Author属性却是Author对象类型的,

我们用的解决方法是通过Book.Auther对象来取得Author的Name属性值,然后再赋值给BookViewModel的Author属性,

这样看起行的通,但是想一想,如果打算在以后的开发中把Name拆分成两个-FisrtName和LastName,

那么,呵呵,我们得去把原来的ViewModel对象也拆分成对应的两个字段,然后在项目中找到所有的转换,然后替换。 
那么有什么办法或者工具来帮助我们能够避免这样的情况发生呢?AutoMapper正是符合要求的一款插件。

使用AutoMapper进行映射

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Conautomapper
{
    class Program
    {
        static void Main(string[] args)
        {
            Exmple_One();
            Console.ReadKey();
        }

        static void Exmple_One()
        {
            AutoMapper.Mapper.CreateMap<Book, BookViewModel>()
                .ForMember(t => t.Author, s => s.MapFrom(u => u.Author.Name));

            Book book = new Book()
            {
                Title = "Leesin",
                Author = new Author()
                {
                    Name = "Lee"
                }
            };

            var model = AutoMapper.Mapper.Map<BookViewModel>(book);
        }
    }
    #region Exmple_One
    public class Author
    {
        public string Name { get; set; }
    }
    public class Book
    {
        public string Title { get; set; }
        public Author Author { get; set; }
    }
    public class BookViewModel
    {
        public string Title { get; set; }
        public string Author { get; set; }
    }
    #endregion
}

总结

仅是测试编写,未在项目中实际运用,还有更多未知的问题和操作。

原文地址:https://www.cnblogs.com/masonblog/p/9232591.html