C# AutoMaper简单使用
AutoMapper它是一种对象与对象之间的映射器,让AutoMapper有意思的就是在于它提供了一些将类型A映射到类型B这种无聊的实例,只要B遵循AutoMapper已经建立的惯例,那么大多数情况下就可以进行相互映射了。
安装
nuget搜索AutoMapper.Extensions.Microsoft.DependencyInjection 安装,会自动安装AutoMapper
创建Entities文件夹,新建User Model
namespace Blogs.WebApi.Entities
{
public class Users
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Gender { get; set; }
}
}
创建Dto文件夹,新建UsersDto类,为了掩饰,把FistName和LastName合并为FullName
namespace Blogs.WebApi.Dto
{
public class UsersDto
{
public int ID { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string Gender { get; set; }
}
}
Startup.cs类增加数据库服务
services.AddDbContext<DataContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("Default")));
新建DataContext类,DbContext包含所有的实体映射到数据库表的实体集(DbSet < TEntity >)
using Microsoft.EntityFrameworkCore; namespace Blogs.WebApi.Entities
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{ }
public DbSet<Users> Users { get; set; }
}
}
创建Services文件夹,新建IUsersRepository仓储接口
using System.Collections.Generic;
using System.Threading.Tasks;
using Blogs.WebApi.Entities; namespace Blogs.WebApi.Services
{
public interface IUsersRepository
{
Task<IEnumerable<Users>> GetAllUsers(); //获取所有用户
Task<Users> GetUsersByID(int id); //根据ID查询单个用户
}
}
新建UsersRepository实现IUsersRepository仓储接口
using System.Collections.Generic;
using System.Threading.Tasks;
using Blogs.WebApi.Entities;
using Microsoft.EntityFrameworkCore; namespace Blogs.WebApi.Services
{
public class UsersRepository : IUsersRepository
{
private readonly DataContext _dataContext; public UsersRepository(DataContext dataContext)
{
_dataContext = dataContext;
}
public async Task<IEnumerable<Users>> GetAllUsers()
{
return await _dataContext.Users.AsNoTracking().ToListAsync();
} public async Task<Users> GetUsersByID(int id)
{
return await _dataContext.Users.AsNoTracking().FirstOrDefaultAsync(u => u.ID == id);
}
}
}
Startup.cs类注入服务依赖
//每次请求,都获取一个新的实例。同一个请求获取多次会得到相同的实例
services.AddScoped<IUsersRepository, UsersRepository>();
//获取已加载到此应用程序域的执行上下文中的程序集。详情AppDomain.GetAssemblies 方法
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
新建Profiles文件夹创建UserProfile类创建映射,继承自Profile类映射集合
using AutoMapper;
using Blogs.WebApi.Dto;
using Blogs.WebApi.Entities; namespace Blogs.WebApi.Profiles
{
public class UserProfile : Profile
{
public UserProfile()
{
CreateMap<Users, UsersDto>()
.ForMember(
dest => dest.FullName, opt =>
{
opt.MapFrom(s => s.FirstName + "." + s.LastName);
});
}
}
}
从Controller文件夹创建UsersController控制器
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Blogs.WebApi.Dto;
using Blogs.WebApi.Services;
using Microsoft.AspNetCore.Mvc; namespace Blogs.WebApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly IUsersRepository _usersRepository;
private readonly IMapper _mapper; public UsersController(IUsersRepository usersRepository, IMapper mapper)
{
_usersRepository = usersRepository;
_mapper = mapper;
}
// GET: api/<UsersController>
[HttpGet]
public async Task<ActionResult<IEnumerable<UsersDto>>> Get()
{
var users = await _usersRepository.GetAllUsers();
return _mapper.Map<IEnumerable<UsersDto>>(users).ToList();
} // GET api/<UsersController>/5
[HttpGet("{id}")]
public async Task<ActionResult<UsersDto>> Get(int id)
{
var user = await _usersRepository.GetUsersByID(id);
return _mapper.Map<UsersDto>(user);
}
}
}
PostMan效果展示


入门讲解推荐视频https://www.bilibili.com/video/BV1XJ411q7yy?p=12
C# AutoMaper简单使用的更多相关文章
- 【造轮子】打造一个简单的万能Excel读写工具
大家工作或者平时是不是经常遇到要读写一些简单格式的Excel? shit!~很蛋疼,因为之前吹牛,就搞了个这东西,还算是挺实用,和大家分享下. 厌烦了每次搞简单类型的Excel读写?不怕~来,喜欢流式 ...
- Fabio 安装和简单使用
Fabio(Go 语言):https://github.com/eBay/fabio Fabio 是一个快速.现代.zero-conf 负载均衡 HTTP(S) 路由器,用于部署 Consul 管理的 ...
- node.js学习(三)简单的node程序&&模块简单使用&&commonJS规范&&深入理解模块原理
一.一个简单的node程序 1.新建一个txt文件 2.修改后缀 修改之后会弹出这个,点击"是" 3.运行test.js 源文件 使用node.js运行之后的. 如果该路径下没有该 ...
- 哪种缓存效果高?开源一个简单的缓存组件j2cache
背景 现在的web系统已经越来越多的应用缓存技术,而且缓存技术确实是能实足的增强系统性能的.我在项目中也开始接触一些缓存的需求. 开始简单的就用jvm(java托管内存)来做缓存,这样对于单个应用服务 ...
- 在Openfire上弄一个简单的推送系统
推送系统 说是推送系统有点大,其实就是一个消息广播功能吧.作用其实也就是由服务端接收到消息然后推送到订阅的客户端. 思路 对于推送最关键的是服务端向客户端发送数据,客户端向服务端订阅自己想要的消息.这 ...
- 我的MYSQL学习心得(一) 简单语法
我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(四) 数据类型 我的MYSQL学习心得(五) 运 ...
- 使用 Nodejs 搭建简单的Web服务器
使用Nodejs搭建Web服务器是学习Node.js比较全面的入门教程,因为要完成一个简单的Web服务器,你需要学习Nodejs中几个比较重要的模块,比如:http协议模块.文件系统.url解析模块. ...
- ASP.NET Aries 入门开发教程2:配置出一个简单的列表页面
前言: 朋友们都期待我稳定地工作,但创业公司若要躺下,也非意念可控. 若人生注定了风雨飘摇,那就雨中前行了. 最机开始看聊新的工作机会,欢迎推荐,创业公司也可! 同时,趁着自由时间,抓紧把这系列教程给 ...
- 简单入门canvas - 通过刮奖效果来学习
一 .前言 一直在做PC端的前端开发,从互联网到行业软件.最近发现移动端已经成为前端必备技能了,真是不能停止学习.HTML5新增的一些东西,canvas是用的比较多也比较复杂的一个,简单的入门了一下, ...
随机推荐
- C++ //纯虚函数和抽象类 // 语法 virtual 返回值类型 函数名 (参数列表)=0 //当类中有了纯虚函数 这个类也称为抽象类
1 //纯虚函数和抽象类 2 // 语法 virtual 返回值类型 函数名 (参数列表)=0 3 //当类中有了纯虚函数 这个类也称为抽象类 4 5 6 #include <iostream& ...
- 阿里钉钉Android实习面试也太太太太难了吧,对算法的要求堪比字节
本人研究生在读,在2月26日找了师兄内推阿里钉钉团队,28号接到了约1面的电话.幸好我提前准备了一个多月的样子,刷面试题.刷LeetCode(面了之后才觉得自己刷少了),对于我这样一个实习生来说题目还 ...
- MySQL Replication Thread States
1.主节点线程状态(Replication Master Thread States): Finished reading one binlog; switching to next binlog 线 ...
- 使用Freemarker导出Word文档(包含图片)代码实现及总结
.personSunflowerP { background: rgba(51, 153, 0, 0.66); border-bottom: 1px solid rgba(0, 102, 0, 1); ...
- rancher2.2.2搭建pipeline
1.通过docker容器安装gitlab代码库 docker run --detach \--hostname 192.168.102.62 \ --env GITLAB_OMNIBUS_CONFIG ...
- Shell-02-数据类型
shell数据类型 shell常用的数据类型有 字符串.整数型.数组 字符串 字符串是shell编程中最常用最有用的数据类型,字符串可以用单引号,也可以用双引号,也可以不用引号 建议使用双引号,因为双 ...
- 【Vulhub】Rsync未授权访问漏洞复现
Rsync未授权访问 Rsync简介 rsync,remote synchronize顾名思意就知道它是一款实现远程同步功能的软件,它在同步文件的同时,可以保持原来文件的权限.时间.软硬链接等附加信息 ...
- COM笔记-引用计数
参考网站:https://www.cnblogs.com/fangyukuan/archive/2010/06/06/1752621.html com组件将维护一个称作是引用计数的数值.当客户从组件取 ...
- 信号量-Semaphore、SemaphoreSlim
核心类:Semaphore,通过int数值来控制线程个数. * 通过观察构造函数 public Semaphore(int initialCount, int maximumCount);: * in ...
- Ajax 与 Struts 1
Xml配置 <action path="/product/product/validateCurrencyDecimalSupport" type="com.neu ...