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);
            }
  • 相关阅读:
    优化网站性能的14条准则
    单元测试
    无配置wcf Host
    .net 4.0
    Java 7 resources
    关于重用
    用GMaven plugin更好地编译系统
    关于系统分层的自问自答
    UBIQUITOUS LANAGUAGE
    用Groovy方式实现接口便于单元测试和协作开发
  • 原文地址:https://www.cnblogs.com/MingqiSs/p/7978336.html
Copyright © 2011-2022 走看看