我想知道如何构建我的MVC控制器方法,以便在找不到请求的数据时,将它们与我的服务层和数据存储库层很好地结合,这被认为是“最佳实践”。
我已经阅读了很多关于如何不使用异常来控制程序流的内容。然而,我已经看到许多示例,代码的结构如下所示......
例如,在GetById控制器方法的情况下,并且id不存在 - 服务层是否应该抛出异常?数据层存储库是否应该抛出异常?然后控制器应该抓住那个?或者这被认为是不好的做法?
例如,这是我的控制器:
public IActionResult Get(int id)
{
EmployeeViewModel pool;
try
{
employee = _employeeService.GetEmployeeById(id);
}
catch (KeyNotFoundException e)
{
return NotFound(e.message);
}
return Ok();
}
这是我的服务层方法:
public EmployeeViewModel GetEmployeeById(int id)
{
var employee = _employeeRepository.GetEmployeeById(id);
if(employee == null)
throw new KeyNotFoundException("Employee not found"); // ok?
var employeelViewModel = Mapper.Map<Employee, EmployeeViewModel>(employee);
return employeeViewModel;
}
这是数据存储库方法:
public Employee GetEmployeeById(int id)
{
var employee =_context.Employees.SingleOrDefault(e => e.Id == id);
if(employee == null)
throw new KeyNotFoundException("Employee with given id does not exist"); // ok?
return employee;
}
或者我应该创建一个额外的服务/ repo方法来首先检查控制器中是否存在具有该id的对象,而不必担心在服务层或数据存储库层中抛出异常。
例如
public ActionResult Get(int id)
{
if (id == 0)
return BadRequest(new ApiResponse("Invalid EmployeeId"));
if (!_employeeService.EmployeeExists(id))
return NotFound("Employee not found"));
employees = _employeeService.GetEmployeeById(id);
return Ok(employees);
}
服务层方法:
public bool EmployeeExists(int id)
{
return _employeeRepository.EmployeeExists(id);
}
public EmployeeViewModel GetEmployeeById(int id)
{
var employee = _employeeRepository.GetEmployeeById(id);
// no check for null or throwing exception
var employeelViewModel = Mapper.Map<Employee, EmployeeViewModel>(employee);
return employeeViewModel;
}
数据存储库方法:
public bool EmployeeExists(int id)
{
return _context.Employees.Count(c => c.Id == id) > 0;
}
public Employee GetEmployeeById(int id)
{
// no check for null or throwing exception
return _context.Employees.SingleOrDefault(e => e.Id == id);
}