使用 DTOS 将数据从存储库获取到服务层

ozi*_*x06 5 c# asp.net model-view-controller repository-pattern asp.net-web-api

我正在学习 ASP.NET 存储库模式。我做了一些研究,但找不到正确的答案。

我的 DAL 上有一个数据库实体 Employee,它有许多列。我有 EmployeeRepository 负责使用 DBContext 查询数据。

现在我的服务层上有 EmployeeService,它需要为员工返回一个 DTO,也就是说,它只有几个字段。(名字、姓氏、出生日期)。

现在,如果我从 EmployeeRepository 中以 IQueryable 的形式获取员工列表,并在服务层上将它们选择为 EmployeeDTO,那么我将通过启用服务层访问数据库来违反规则。

如果没有,则 EmployeeRepository 会将每个员工的所有数据以列表的形式返回给服务层,以便服务层只选择少数字段来创建 EmployeeDTO。但在这种方法中,我将加载所有不需要的数据。

我想知道是否有人有建议。

亲切的问候,

Rol*_*ndo 0

我认为您应该从存储库中仅返回您需要的列。之后在您的服务中映射到正确的 Dto。我觉得这个话题有很多不同的观点,而且有点难。在下面的示例中,没有服务,只有存储库和 API 控制器。

    [HttpGet("{id}")]
    public IActionResult GetCity(int id, bool includePointsOfInterest = false)
    {
        var city = _cityInfoRepository.GetCity(id, includePointsOfInterest);

        if (city == null)
        {
            return NotFound();
        }

        if (includePointsOfInterest)
        {
            var cityResult = Mapper.Map<CityDto>(city); 
            return Ok(cityResult);
        }

        var cityWithoutPointsOfInterestResult = Mapper.Map<CityWithoutPointsOfInterestDto>(city);
        return Ok(cityWithoutPointsOfInterestResult);
    }
Run Code Online (Sandbox Code Playgroud)