.NET CORE中使用AutoMapper进行对象映射的方法

2025-05-29 0 52

简介

AutoMapper uses a fluent configuration API to define an object-object mapping strategy. AutoMapper uses a convention-based matching algorithm to match up source to destination values. AutoMapper is geared towards model projection scenarios to flatten complex object models to DTOs and other simple objects, whose design is better suited for serialization, communication, messaging, or simply an anti-corruption layer between the domain and application layer.

官网:http://automapper.org/

文档:https://automapper.readthedocs.io/en/latest/index.html

GitHub:https://github.com/AutoMapper/AutoMapper/blob/master/docs/index.rst

平台支持:

  • .NET 4.6.1+
  • .NET Standard 2.0+ https://docs.microsoft.com/en-us/dotnet/standard/net-standard

使用

Nuget安装

?

1

2
AutoMapper

AutoMapper.Extensions.Microsoft.DependencyInjection //依赖注入AutoMapper,需要下载该包。

在Startup中添加AutoMapper

?

1

2

3

4

5

6
public void ConfigureServices(IServiceCollection services)

{

services.AddMvc();

//添加对AutoMapper的支持

services.AddAutoMapper();

}

创建AutoMapper映射规则

?

1

2

3

4

5

6

7

8

9
public class AutoMapperConfigs:Profile

{

//添加你的实体映射关系.

public AutoMapperConfigs()

{

CreateMap<DBPoundSheet, PoundSheetViewModel>();

CreateMap<PoundSheetViewModel, DBPoundSheet>();

}

}

在构造函数中注入你的IMapper

?

1

2

3

4

5

6
IMapper _mapper;

public PoundListController(IMapper mapper)

{

_mapper = mapper;

}

单个对象转换

?

1

2
//typeof(model)="PoundSheetViewModel"

DBPoundSheet dBPoundSheet = _mapper.Map<DBPoundSheet>(model);

集合对象转换

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对快网idc的支持。

原文链接:https://www.cnblogs.com/wyt007/p/10123451.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 .NET CORE中使用AutoMapper进行对象映射的方法 https://www.kuaiidc.com/98737.html

相关文章

猜你喜欢
发表评论
暂无评论