在DoNetCore MVC 中如何使用AutoMapper
刚开始,按照在donet mvc 的方法写了一遍,发现行不通啊,于是百度了一下,找到这么一篇 https://stackoverflow.com/questions/41284349/automapper-error-saying-mapper-not-initialized
动手开干 ,具体流程
1、Nuget 引入包
Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection
2、创建我们的源数据实体,创建我们的目标实体
这是我的项目目录信息,其中红框中就是我们的源实体和目标实体
3、注入服务
在Startup.cs 类中 ConfigureServices 方法中最后一行 添加如下代码:
services.AddAutoMapper();
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
}); //services.AddTransient<IAdminBusinessLoginService, AdminBusinessLoginService>(); var redisconn = Configuration.GetSection("RedisConnectionStrings");
services.AddOptions();
services.Configure<RedisConnectionStrings>(redisconn); var opt = Configuration.GetSection("RedisConnectionStrings"); //Models.AutoMapperHelper.AutoMapperConfig.RegisterAutoMapper(); services.AddSingleton<ICache, ICCSReidsiHelper>(); services.AddAssembly("DSErpService");
services.AddAssembly("IDSErpService");
//注入上下文对象
var sqlConnection = Configuration.GetConnectionString("SchoolConnection");
services.AddDbContext<Db>(op => op.UseSqlServer(sqlConnection)); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
//前台用户cookie服务
.AddCookie(UserAuthorizeAttribute.UserAuthenticationScheme, options =>
{
options.LoginPath = "/Login/Index";
options.LogoutPath = "/Login/LogOff";
options.AccessDeniedPath = new PathString("/Error/Forbidden");//拒绝访问页面
options.Cookie.Path = "/";
}); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddAutoMapper();
}
如图:

4、创建我们的映射对象
这里直接上代码:
public class CategoryProfiles : Profile
{
public CategoryProfiles()
{
CreateMap<BusinessCategory, CategoryDto>().ReverseMap()
.ForMember(a => a.Id, b => b.MapFrom(c => c.Id))
.ForMember(a => a.CategoryName, b => b.MapFrom(c => c.CategoryName))
.ForMember(a => a.StatusMark, b => b.MapFrom(c => c.StatusMark));
}
}
5、实现
[Route("category")]
public class categoryController : Controller
{
/// <summary>
/// 获取用户缓存信息
/// </summary>
private ICache cache;
/// <summary>
/// 分类服务管理
/// </summary>
private ICategoryService categoryService;
private readonly IMapper _mapper;
public categoryController(ICache _cache, ICategoryService _service, IMapper mapper)
{
this.cache = _cache;
this.categoryService = _service;
this._mapper = mapper;
}
[HttpGet("get-pagelist")]
public async Task<JsonResult> GetCategoryPageList(int pageindex, int pagesize)
{
return await Task.Run<JsonResult>(() =>
{
var totalcount = ;
var reslist = this.categoryService.GetCategroryList(null, pageindex, pagesize, out totalcount);
return Json(new
{
code = ,
msg = "",
count = totalcount,
data = this._mapper.Map<List<CategoryDto>>(reslist.data)
});
});
}
}
说明:
this._mapper.Map<List<CategoryDto>>(reslist.data) 我这里是集合映射到集合 ,
this._mapper.Map<T>(T);
this._mapper.Map<List<T>>(listT);
在DoNetCore MVC 中如何使用AutoMapper的更多相关文章
- AutoMapper在MVC中的运用01-配置、使用、单元测试、举例
MVC中,如果想在Domain Model和View Model之间建立映射,用AutoMapper是一个不错的选择.不仅如此,AutoMapper能在不同对象之间建立映射,比如string与int类 ...
- ADO.NET .net core2.0添加json文件并转化成类注入控制器使用 简单了解 iTextSharp实现HTML to PDF ASP.NET MVC 中 Autofac依赖注入DI 控制反转IOC 了解一下 C# AutoMapper 了解一下
ADO.NET 一.ADO.NET概要 ADO.NET是.NET框架中的重要组件,主要用于完成C#应用程序访问数据库 二.ADO.NET的组成 ①System.Data → DataTable, ...
- MVC 中的 ViewModel
此文章总结自:http://rachelappel.com/use-viewmodels-to-manage-data-amp-organize-code-in-asp.net-mvc-applica ...
- MVC中验证码
MVC中验证码的实现(经常用,记录备用) 一.目录 1.多层架构+MVC+EF+AUTOFAC+AUTOMAPPER: 2.MVC中验证码的实现(经常用,记录备用) 3.Ligerui首页的快速搭 ...
- MVC中验证码的实现(经常用,记录备用)
一.目录 1.多层架构+MVC+EF+AUTOFAC+AUTOMAPPER: 2.MVC中验证码的实现(经常用,记录备用) 3.Ligerui首页的快速搭建 二 正文 Ok,我们的验证码开始,这篇文章 ...
- .NetCore MVC中的路由(2)在路由中使用约束
p { margin-bottom: 0.25cm; direction: ltr; color: #000000; line-height: 120%; orphans: 2; widows: 2 ...
- .NetCore MVC中的路由(1)路由配置基础
.NetCore MVC中的路由(1)路由配置基础 0x00 路由在MVC中起到的作用 前段时间一直忙于别的事情,终于搞定了继续学习.NetCore.这次学习的主题是MVC中的路由.路由是所有MVC框 ...
- Asp.Net MVC中使用StreamReader读取“Post body”之应用场景。
场景:有三个市场(Global.China.USA),对前台传过来的数据有些验证需要细化到每个市场去完成. 所以就出现了基类(Global)和派生类(China.USA) 定义基类(Global)Pe ...
- 6.在MVC中使用泛型仓储模式和依赖注入实现增删查改
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...
随机推荐
- Xamarin.FormsShell基础教程(7)Shell项目关于页面的介绍
Xamarin.FormsShell基础教程(7)Shell项目关于页面的介绍 轻拍标签栏中的About标签,进入关于页面,如图1.8和图1.9所示.它是对应用程序介绍的页面. 该页面源自Views文 ...
- js比较时间大于6个月
//mons是比较的月数,如 2019-02-01 14:27:08 - 2019-08-01 14:27:08 function compareTime(mons,stTime,endTime){ ...
- SpringBoot Error creating bean with name 'dataSource' defined in class path resource。。。
启动spring boot项目出错 解决方法在Application类上增加:@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration ...
- mysql数据库架构设计与优化
mysql数据库架构设计与优化 2019-04-23 20:51:20 无畏D尘埃 阅读数 179 收藏 更多 分类专栏: MySQL 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA ...
- Egret《决战沙城》框架学习
源码地址:https://github.com/yicaoyimuys/EgretGameEngine 虽然走花观马看了看,但是收获还是蛮多. mvc: BaseController ...
- Spark Streaming反压机制
反压(Back Pressure)机制主要用来解决流处理系统中,处理速度比摄入速度慢的情况.是控制流处理中批次流量过载的有效手段. 1 反压机制原理 Spark Streaming中的反压机制是Spa ...
- Centos7基础之查看NETMASK,GATWAY,DNS小技巧
引语: 查看IP这种很基础的操作,想必大家都快倒背如流了.就是不知道大家知不知道怎么查看NETMASK,GATWAY,DNS.当然nmtui图形化界面以及查看网络配置文件这种骚操作就直接略过了.之前一 ...
- CentOS 7.5 使用 yum 安装 Kubernetes 集群(二)
一.安装方式介绍 1.yum 安装 目前CentOS官方已经把Kubernetes源放入到自己的默认 extras 仓库里面,使用 yum 安装,好处是简单,坏处也很明显,需要官方更新 yum 源才能 ...
- csu 1976: 搬运工小明
1976: 搬运工小明 Submit Page Summary Time Limit: 2 Sec Memory Limit: 128 Mb Submitted: 94 ...
- SpringBoot系列教程web篇之全局异常处理
当我们的后端应用出现异常时,通常会将异常状况包装之后再返回给调用方或者前端,在实际的项目中,不可能对每一个地方都做好异常处理,再优雅的代码也可能抛出异常,那么在 Spring 项目中,可以怎样优雅的处 ...