在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();
1 // This method gets called by the runtime. Use this method to add services to the container. 2 public void ConfigureServices(IServiceCollection services) 3 { 4 services.Configure<CookiePolicyOptions>(options => 5 { 6 // This lambda determines whether user consent for non-essential cookies is needed for a given request. 7 options.CheckConsentNeeded = context => true; 8 options.MinimumSameSitePolicy = SameSiteMode.None; 9 }); 10 11 //services.AddTransient<IAdminBusinessLoginService, AdminBusinessLoginService>(); 12 13 14 var redisconn = Configuration.GetSection("RedisConnectionStrings"); 15 services.AddOptions(); 16 services.Configure<RedisConnectionStrings>(redisconn); 17 18 var opt = Configuration.GetSection("RedisConnectionStrings"); 19 20 //Models.AutoMapperHelper.AutoMapperConfig.RegisterAutoMapper(); 21 22 services.AddSingleton<ICache, ICCSReidsiHelper>(); 23 24 services.AddAssembly("DSErpService"); 25 services.AddAssembly("IDSErpService"); 26 //注入上下文对象 27 var sqlConnection = Configuration.GetConnectionString("SchoolConnection"); 28 services.AddDbContext<Db>(op => op.UseSqlServer(sqlConnection)); 29 30 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) 31 //前台用户cookie服务 32 .AddCookie(UserAuthorizeAttribute.UserAuthenticationScheme, options => 33 { 34 options.LoginPath = "/Login/Index"; 35 options.LogoutPath = "/Login/LogOff"; 36 options.AccessDeniedPath = new PathString("/Error/Forbidden");//拒绝访问页面 37 options.Cookie.Path = "/"; 38 }); 39 40 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); 41 services.AddAutoMapper(); 42 }
如图:
4、创建我们的映射对象
这里直接上代码:
1 public class CategoryProfiles : Profile 2 { 3 public CategoryProfiles() 4 { 5 CreateMap<BusinessCategory, CategoryDto>().ReverseMap() 6 .ForMember(a => a.Id, b => b.MapFrom(c => c.Id)) 7 .ForMember(a => a.CategoryName, b => b.MapFrom(c => c.CategoryName)) 8 .ForMember(a => a.StatusMark, b => b.MapFrom(c => c.StatusMark)); 9 } 10 }
5、实现
1 [Route("category")] 2 public class categoryController : Controller 3 { 4 /// <summary> 5 /// 获取用户缓存信息 6 /// </summary> 7 private ICache cache; 8 /// <summary> 9 /// 分类服务管理 10 /// </summary> 11 private ICategoryService categoryService; 12 private readonly IMapper _mapper; 13 public categoryController(ICache _cache, ICategoryService _service, IMapper mapper) 14 { 15 this.cache = _cache; 16 this.categoryService = _service; 17 this._mapper = mapper; 18 } 19 20 21 [HttpGet("get-pagelist")] 22 public async Task<JsonResult> GetCategoryPageList(int pageindex, int pagesize) 23 { 24 return await Task.Run<JsonResult>(() => 25 { 26 var totalcount = 0; 27 var reslist = this.categoryService.GetCategroryList(null, pageindex, pagesize, out totalcount); 28 return Json(new 29 { 30 code = 0, 31 msg = "", 32 count = totalcount, 33 data = this._mapper.Map<List<CategoryDto>>(reslist.data) 34 }); 35 }); 36 } 37 }
说明:
this._mapper.Map<List<CategoryDto>>(reslist.data) 我这里是集合映射到集合 ,
this._mapper.Map<T>(T);
this._mapper.Map<List<T>>(listT);