Asp.net mvc 在带有EF Core应用程序的简单ASP.NET Core MVC中使用DTO和AutoMapper
我是ASP.NET Core的新手,在创建数据库时,我使用代码优先的方法使用EF Core应用程序构建了一个ASP.NET Core MVC 现在,我想在这个简单的应用程序中使用DTOs和AutoMapper 在下面的代码中,您可以从模型文件夹中找到Employee.cs:Asp.net mvc 在带有EF Core应用程序的简单ASP.NET Core MVC中使用DTO和AutoMapper,asp.net-mvc,asp.net-core,entity-framework-core,automapper,dto,Asp.net Mvc,Asp.net Core,Entity Framework Core,Automapper,Dto,我是ASP.NET Core的新手,在创建数据库时,我使用代码优先的方法使用EF Core应用程序构建了一个ASP.NET Core MVC 现在,我想在这个简单的应用程序中使用DTOs和AutoMapper 在下面的代码中,您可以从模型文件夹中找到Employee.cs: public class Employee { [Key] public int EmployeeId { get; set; } [Column(TypeName =
public class Employee
{
[Key]
public int EmployeeId { get; set; }
[Column(TypeName ="nvarchar(250)")]
[Required(ErrorMessage ="This field is required.")]
[DisplayName("Full Name")]
public string FullName { get; set; }
[Column(TypeName = "varchar(10)")]
[DisplayName("Emp. Code")]
public string EmpCode { get; set; }
[Column(TypeName = "varchar(100)")]
public string Position { get; set; }
[Column(TypeName = "varchar(100)")]
[DisplayName("Office Location")]
public string OfficeLocation { get; set; }
}
您可以在下面找到EmployeeController.cs文件:
public class EmployeeController : Controller
{
private readonly EmployeeContext _context;
public EmployeeController(EmployeeContext context)
{
_context = context;
}
// GET: Employee
public async Task<IActionResult> Index()
{
return View(await _context.Employees.ToListAsync());
}
// GET: Employee/Create
public IActionResult AddOrEdit(int id = 0)
{
if (id == 0)
return View(new Employee());
else
return View(_context.Employees.Find(id));
}
// POST: Employee/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddOrEdit([Bind("EmployeeId,FullName,EmpCode,Position,OfficeLocation")] Employee employee)
{
if (ModelState.IsValid)
{
if (employee.EmployeeId == 0)
_context.Add(employee);
else
_context.Update(employee);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(employee);
}
// GET: Employee/Delete/5
public async Task<IActionResult> Delete(int? id)
{
var employee =await _context.Employees.FindAsync(id);
_context.Employees.Remove(employee);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddDbContext<EmployeeContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Employee}/{action=Index}/{id?}");
});
}
}
公共类EmployeeController:控制器
{
私有只读EmployeeContext_context;
公共EmployeeController(EmployeeContext上下文)
{
_上下文=上下文;
}
//获取:员工
公共异步任务索引()
{
返回视图(wait_context.Employees.toListSync());
}
//获取:员工/创建
公共IActionResult AddOrEdit(int id=0)
{
如果(id==0)
返回视图(新员工());
其他的
返回视图(_context.Employees.Find(id));
}
//职位:员工/创建
//若要防止套印攻击,请启用要绑定到的特定属性,例如
//更多详细信息请参见http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务AddOrEdit([Bind(“EmployeeId,全名,EmpCode,Position,OfficeLocation”)]Employee-Employee)
{
if(ModelState.IsValid)
{
如果(employee.EmployeeId==0)
_上下文。添加(员工);
其他的
_上下文更新(员工);
wait_context.SaveChangesAsync();
返回重定向到操作(名称(索引));
}
返回视图(员工);
}
//获取:Employee/Delete/5
公共异步任务删除(int?id)
{
var employee=wait_context.Employees.FindAsync(id);
_context.Employees.Remove(雇员);
wait_context.SaveChangesAsync();
返回重定向到操作(名称(索引));
}
}
此外,您可以在下面找到Startup.cs文件:
public class EmployeeController : Controller
{
private readonly EmployeeContext _context;
public EmployeeController(EmployeeContext context)
{
_context = context;
}
// GET: Employee
public async Task<IActionResult> Index()
{
return View(await _context.Employees.ToListAsync());
}
// GET: Employee/Create
public IActionResult AddOrEdit(int id = 0)
{
if (id == 0)
return View(new Employee());
else
return View(_context.Employees.Find(id));
}
// POST: Employee/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddOrEdit([Bind("EmployeeId,FullName,EmpCode,Position,OfficeLocation")] Employee employee)
{
if (ModelState.IsValid)
{
if (employee.EmployeeId == 0)
_context.Add(employee);
else
_context.Update(employee);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(employee);
}
// GET: Employee/Delete/5
public async Task<IActionResult> Delete(int? id)
{
var employee =await _context.Employees.FindAsync(id);
_context.Employees.Remove(employee);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddDbContext<EmployeeContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Employee}/{action=Index}/{id?}");
});
}
}
公共类启动
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
配置(选项=>
{
//此lambda确定给定请求是否需要非必要cookie的用户同意。
options.checkApprovered=context=>true;
options.MinimumSameSitePolicy=SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddDbContext(选项=>
options.UseSqlServer(Configuration.GetConnectionString(“DevConnection”));
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“默认”,
模板:“{controller=Employee}/{action=Index}/{id?}”);
});
}
}
为了使用DTO和AutoMapper,我应该对我的应用程序进行哪些更改
请让我知道您是否需要应用程序中的其他文件
谢谢。您可以执行以下步骤
安装包AutoMapper.Extensions.Microsoft.DependencyInjection
注意:如果我们安装AutoMapper.Extensions.Microsoft.DependencyInjection包,它将自动为我们安装AutoMapper包,因为它引用了它
代码>
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Employee, EmployeeDTO>();
CreateMap<EmployeeDTO, Employee>();
}
}
首先,我们将映射器对象注入控制器。然后,我们调用Map()方法,将Employee对象映射到EmployeeDTO对象
公共类EmployeeController:控制器
{
私有只读EmployeeContext_context;
专用只读IMapper\u映射器;
公共EmployeeController(EmployeeContext上下文,IMapper映射器)
{
_上下文=上下文;
_映射器=映射器;
}
//获取:员工
公共异步任务索引()
{
List employees=_mapper.Map(wait_context.employees.toListSync());
返回视图(员工);
}
}
您可以执行以下步骤
创建你的EmployeeDTO.cs
安装相应的NuGet软件包
安装包AutoMapper.Extensions.Microsoft.DependencyInjection
注意:如果我们安装AutoMapper.Extensions.Microsoft.DependencyInjection包,它将自动为我们安装AutoMapper包,因为它引用了它
创建MappingProfile.cs
使用AutoMapper添加代码>
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Employee, EmployeeDTO>();
CreateMap<EmployeeDTO, Employee>();
}
}
首先,我们将映射器对象注入控制器。然后,我们调用Map()方法,将Employee对象映射到EmployeeDTO对象
公共类EmployeeController:控制器
{
私有只读EmployeeContext_context;
专用只读IMapper\u映射器;
公共EmployeeController(EmployeeContext上下文),IMapper ma