zoukankan      html  css  js  c++  java
  • .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);
            }
  • 相关阅读:
    Maven入门
    Windows Java安装
    cdh安装spark遇到的几个BUG
    SQL Server创建存储过程——动态SQL
    IDEA搭建scala开发环境开发spark应用程序
    liunx命令
    java常用 api
    缓存一致性问题
    git 命令
    nginx
  • 原文地址:https://www.cnblogs.com/MingqiSs/p/7978336.html
Copyright © 2011-2022 走看看