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); }