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效果展示
本文来自博客园,作者:liessay,转载请注明原文链接:https://www.cnblogs.com/liessay/p/13048817.html