【发布时间】:2018-08-24 09:01:09
【问题描述】:
我正在学习 C#.NET Core 并尝试在不使用 AutoMapper 的情况下创建 DTO 映射,因为我正在单独处理一个小项目并且想在使用额外包之前了解基础知识,令人惊讶的是我无法在 stackoverflow 上轻松找到答案。 com,否则我可能会使用错误的关键字搜索。
顺便说一句,下面是我在 GetEmployee 方法下成功映射到 EmployeeForShortDto 的代码。不幸的是,我不知道如何将它映射到 GetAllEmployee 下,因为返回数据是一个集合,而不是单个记录。请指教。
EmployeeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NetCoreWebApplication1.Dto;
using NetCoreWebApplication1.Repository;
using NetCoreWebApplication1.Other;
namespace NetCoreWebApplication1.Controller
{
[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase
{
private readonly IMasterRepository _repo;
public EmployeeController(IMasterRepository repo)
{
_repo = repo;
}
[HttpGet("{id}")]
public async Task<IActionResult> GetEmployee(int id)
{
var data = await _repo.GetEmployee(id);
if (data == null) return NotFound();
var dataDto = new EmployeeForShortDto()
{
Id = data.Id,
EmpCode = data.EmpCode,
Fname = data.Fname,
Lname = data.Lname,
Age = NetCoreWebApplication1.Other.Extension.CalcAge(data.DateBirth)
};
return Ok(dataDto);
}
[HttpGet]
public async Task<IActionResult> GetAllEmployee()
{
var data = await _repo.GetAllEmployee();
return Ok(data);
}
}
}
MasterRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using NetCoreWebApplication1.Models;
namespace NetCoreWebApplication1.Repository
{
public class MasterRepository : IMasterRepository
{
private readonly PrDbContext _context;
public MasterRepository(PrDbContext context)
{
_context = context;
}
// Employee
public async Task<List<Employee>> GetAllEmployee()
{
var data = await _context.Employee.ToListAsync();
return data;
}
public async Task<Employee> GetEmployee(int id)
{
var data = await _context.Employee.FirstOrDefaultAsync(x => x.Id == id);
return data;
}
// Generic methods
public void Add<T>(T entity) where T : class
{
_context.Add(entity);
}
public void Delete<T>(T entity) where T : class
{
_context.Remove(entity);
}
public async Task<bool> SaveAll()
{
return await _context.SaveChangesAsync() > 0;
}
}
}
【问题讨论】:
-
仅供参考,您应该让您的 GetAllEmployee 和 GetEmployee 像其他人一样通用。我认为您唯一的选择是编写一个 for 循环,将其映射到所需类型的集合中。手动和痛苦。
标签: c# asp.net-core dto