如何在 C# 中使用 AutoMapper

proginn468312

共 4576字,需浏览 10分钟

 · 2020-11-28

译文链接:https://www.infoworld.com/article/3192900/how-to-work-with-automapper-in-csharp.html

AutoMapper 是一个非常流行的 object-to-object 映射库,它的目的就是帮助你实现不同类型对象之间的映射,举一个例子,在 DDD 开发模式中,你可能需要实现将 DTO object 映射为 Model object,在过去,你需要人肉的将这两个类型下的属性字段进行一一映射,现在 AutoMapper 就可以帮你节省 这种冗余的模板式代码 匹配所耗费的时间。

开始玩 AutoMapper 之前,你需要在 Visual Studio 中创建一个 Project 并且安装 AutoMapper,你可以从 NuGet 上下载,也可以在 NuGet Package Manager Console 控制台输入如下命令:


PM> Install-Package AutoMapper

使用 AutoMapper 创建映射关系

像 AutoMapper 这样的 object-to-object 映射工具,它必须能够做到将一种输入类型转换成另一个输出类型,是不是很拗口,可以先考虑下面的两个类。


    public class AuthorModel
    {
        public int Id
        {
            getset;
        }
        public string FirstName
        {
            get;set;
        }
        public string LastName
        {
            getset;
        }
        public string Address
        {
            getset;
        }
    }

    public class AuthorDTO
    {
        public int Id
        {
            getset;
        }
        public string FirstName
        {
            getset;
        }
        public string LastName
        {
            getset;
        }
        public string Address
        {
            getset;
        }
    }

接下来,下面的代码段将会告知你如何使用 AutoMapper 在 AuthorModel  和 AuthorDTO 这两个对象之间创建一个 mapping 关系。


var config = new MapperConfiguration(cfg => {
                cfg.CreateMap();
            });

最终的 mapping 转换,你还需要增加几句下面的代码,实现两个类型之间的转换。


IMapper iMapper = config.CreateMapper();
var source = new AuthorModel();
var destination = iMapper.Map(source);

一个 AutoMapper 的例子

接下来可以上一些数据了,可以参考下面的代码片段,我准备先在 source object 上赋值,然后执行 AutoMapper 中的 Map 方法之后,在 destination object 上原样显示出来。


var config = new MapperConfiguration(cfg => {
                cfg.CreateMap();
            });
IMapper iMapper = config.CreateMapper();
var source = new AuthorModel();
source.Id = 1;
source.FirstName = "Joydip";
source.LastName = "Kanjilal";
source.Address = "India";
var destination = iMapper.Map(source);
Console.WriteLine("Author Name: "+ destination.FirstName + " " + destination.LastName);

当你执行完这段代码之后,destination  object 上的 Author Name 将会输出到控制台上,目标对象上的 FirstName 和 LastName 和 source object 上的这两个属性值保持一致,说明 automapper 已经帮你成功映射。

值得注意的是,AutoMapper 不仅仅可以 mapping 一个类,还可以 mapping 多个类,默认情况下,AutoMapper会按照默认约定匹配,也就是被mapping的对象之间具有相同的属性名称才能被成功映射,但现实情况下,很多被映射的属性名称是不相同的,这个时候就需要人工介入指定 mapping 关系让 AutoMapper 按照你设定的执行,假定你需要实现 Contact 到 ContactDetails 之间的映射,下面的例子展示了如何去实现这种关系。


var config = new MapperConfiguration(cfg => {
                cfg.CreateMap()
                .ForMember(destination => destination.ContactDetails,
               opts => opts.MapFrom(source => source.Contact));
            });

下面的语句可以创建最终的  destination object 对象。


var destination = iMapper.Map(source);

有时候你已经生成了 destination  object,在这基础上你还想二次映射,这时可以使用下面替代语句。


iMapper.Map(sourceObject, destinationObject);

本质上来说,上面的这段代码常用于匹配两个已存在的 object。

使用 AutoMapping 的 projections 功能

AutoMapper 提供了非常好的 projections 功能,projections ??的地方在于在 mapping 映射时可以无视两者的 object 数据结构是否一致,比如说让 source 的多个属性 映射到 destination 的一个属性上,而上面我们一直讨论的都是一对一的 object mapping。

接下来我们一起学习下 projection,举个例子,考虑如下类。


    public class Address
    {
        public string City { getset; }
        public string State { getset; }
        public string Country { getset; }
    }

接下来在 AuthorModel 类中新增一个 Address 属性用来存储 Author 的地址信息,修改后的 AuthorModel 类如下:


    public class AuthorModel
    {
        public int Id
        {
            getset;
        }
        public string FirstName
        {
            get;set;
        }
        public string LastName
        {
            getset;
        }
        public Address Address
        {
            getset;
        }
    }

然后再更新一下 AuthorDTO  类


    public class AuthorDTO
    {
        public int Id
        {
            getset;
        }
        public string FirstName
        {
            getset;
        }
        public string LastName
        {
            getset;
        }
        public string City { getset; }
        public string State { getset; }
        public string Country { getset; }
    }

接下来我们需要将 AuthorDTO 映射到 AuthorModel,下面的代码片段展示了如何去实现。


var config = new MapperConfiguration(cfg => {
                cfg.CreateMap()
                   .ForMember(destination => destination.Address,
              map => map.MapFrom(
                  source => new Address
                  {
                      City = source .City,
                      State = source .State,
                      Country = source.Country
                  }));

我会在后续的文章中继续讨论 AutoMapper 更多的高级特性,现在,你可以通过这个链接:http://automapper.org/  去学习更多的 AutoMapper 知识。


浏览 8
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报