在具有EF Core应用程序的简单ASP.NET Core MVC中使用DTO和AutoMapper

问题描述 投票:0回答:1

我是ASP.NET Core的新手,在创建数据库时,我使用代码优先方法构建了具有EF Core应用程序的ASP.NET Core MVC。

现在,我想在这个简单的应用程序中使用DTO和AutoMapper。

在下面的代码中,您可以从Models文件夹中找到Employee.cs

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

此外,您可能会在Startup.cs文件下面找到:

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

我应该对我的应用程序进行哪些更改才能使用DTO和AutoMapper?

请让我知道您是否需要该应用程序中的其他文件。

谢谢。

asp.net-mvc asp.net-core entity-framework-core automapper dto
1个回答
-1
投票

您可以执行以下步骤。

  1. 创建您的EmployeeDTO.cs
public class EmployeeDTO
{
    public int EmployeeId { get; set; }
    public string FullName { get; set; }
    public string EmpCode { get; set; }
    public string Position { get; set; }
    public string OfficeLocation { get; set; }
}
  1. 安装相应的NuGet软件包

Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection

注意:如果我们安装AutoMapper.Extensions.Microsoft.DependencyInjection程序包,因为它引用了它,它将自动为我们安装AutoMapper程序包。

  1. 创建MappingProfile.cs

添加using AutoMapper;

public class MappingProfile : Profile
{
    public MappingProfile()
    {
          CreateMap<Employee, EmployeeDTO>();
          CreateMap<EmployeeDTO, Employee>();
    }
}
  1. 配置服务。让我们在Startup.cs类中进行操作。
services.AddAutoMapper(typeof(Startup));
  1. 首先,我们将映射器对象注入控制器。然后,我们调用Map()方法,该方法将Employee对象映射到EmployeeDTO对象。
public class EmployeeController : Controller
{
     private readonly EmployeeContext _context;
     private readonly IMapper _mapper;

     public EmployeeController(EmployeeContext context,, IMapper mapper)
     {
         _context = context;
         _mapper = mapper;
     }

     // GET: Employee
     public async Task<IActionResult> Index()
     {

        List<EmployeeDTO> employees = _mapper.Map<List<Employee>, List<EmployeeDTO>>(await _context.Employees.ToListAsync());
        return View(employees);
     }
}
© www.soinside.com 2019 - 2024. All rights reserved.