【发布时间】:2015-09-12 02:00:47
【问题描述】:
我有一个包含部门和员工的 Web API (2) 项目。一个员工有一个部门,一个部门有一个员工列表。
现在在前端,当创建或编辑员工时,用户必须选择一个部门。将此发布到 API 时,部门包含员工列表(这会导致模型状态无效),我该如何防止这种情况发生?
这是我的相关设置:
型号:
public class Employee : IEntity, ICreatedOn, IModifiedOn, IMappable
{
[Key]
public virtual int Id { get; set; }
public virtual Department Department { get; set; }
// .. other properties
}
public class Department : IEntity, IMappable
{
[Key]
public virtual int Id { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
// .. other properties
}
Web API 控制器:
public class EmployeesController : ApiController
{
private readonly IEmployeeService _employeeService;
public EmployeesController(IEmployeeService employeeService)
{
this._employeeService = employeeService;
}
// .. GET, POST, DELETE etc.
// PUT: api/Employees/5
[ResponseType(typeof(void))]
public IHttpActionResult PutEmployee(int id, EmployeeVM employee)
{
// This is always invalid, because the employee has a department, which in turn has a list of employees which can be invalid
// What to do to exclude the list of employees from validation, or even better prevent from being sent to the API
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Update etc..
return StatusCode(HttpStatusCode.NoContent);
}
Angular (DataService.js):
app.factory('DataService',
["$http",
function ($http) {
return {
// other functions
updateEmployee: _updateEmployee
}
function _updateEmployee(employee) {
// Maybe exclude the list of employees in employee.department in here??
return $http.put(employeesUrl + "/" + employee.id, employee);
}
// .. other functions
}]);
注意事项:
- Put 和 Post 中都会发生这种情况(更新和创建)
- 我正在使用 AutoMapper 映射到 ViewModel,它们看起来与实体相同
- 我正在为 ORM 使用实体框架
我尝试过的:
- Employees 集合的[JsonIgnore] 属性;这会导致在加载部门时也不会加载员工
- [Bind(Exclude = "Employees")] 属性在控制器动作参数中,这个没有任何效果
- [绑定(Exclude = "Department.Employees")] 相同
什么可行,但我确信一定有更好的解决方案:
function _updateEmployee(employee) {
var newEmp = angular.copy(employee);
delete newEmp.department.employees;
return $http.put(employeesUrl, newEmp);
}
【问题讨论】:
-
请出示您的 EmployeeVM
标签: angularjs json.net asp.net-web-api2