• .net core使用 AutoMapper


    1.添加AutoMapper的引用

    在Nuget包添加AutoMapper的引用以及引用 AutoMapper 对依赖注入的一个扩展  Extensions.Microsoft.DependencyInjection

    或者程序包管理器控制台添加

    PM> Install-Package AutoMapper

    PM> install-package AutoMapper.Extensions.Microsoft.DependencyInjection

    2.在Startup.cs 文件ConfigureServices添加代码

     public void ConfigureServices(IServiceCollection services)
            {
                //services.AddDbContext<DataContext>(options =>
                //options.UseSqlServer(Configuration.GetConnectionString("SqlServer")));
                services.AddMvc();
               services.AddAutoMapper();
            }

    3.在项目文件添加映射配置类

     public class UserProfile: Profile
        {
            public UserProfile()
            {
              
                CreateMap<Student, NewStudent>();
                CreateMap<NewStudent, Student>();
            }
        }

    4. 在需要的Controller依赖注入就可以使用了

     private readonly DataContext _context;
            private readonly IMapper _mapper;
            public StudentsController(DataContext context, IMapper mapper)
            {
                _context = context;
                _mapper = mapper;
            }
     [HttpPost]
            [ValidateAntiForgeryToken]
            public async Task<IActionResult> Create([Bind("LastName,FirstMidName,EnrollmentDate")] NewStudent student)
            {
    
                if (ModelState.IsValid)
                {
                    var model = _mapper.Map<Student>(student); //映射
                    _context.Add(model);
                    await _context.SaveChangesAsync();
                    return RedirectToAction(nameof(Index));
                }
                return View(student);
            }
  • 相关阅读:
    CentOS7 网络管理相关命令
    CentOS7配置双网卡绑定
    ajax请求
    django向数据库添加数据
    django基于正则的url匹配
    django前端到后端一次简单完整的请求实例
    django数据库动态添加列
    django1.9 创建项目和app并初始化项目
    django1.9 创建数据表
    数据结构和算法(5)-树
  • 原文地址:https://www.cnblogs.com/MingqiSs/p/7978336.html
Copyright © 2020-2023  润新知