我有一個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);
}
角(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
}]);
注意事項:
- 它發生在認沽和後兩者(更新和創造)
- 我使用AutoMapper映射到的ViewModels,看起來一樣的實體
- 我使用實體框架對於ORM
我已經試過:
- [JsonIgnore]在Employees集合屬性;這會導致僱員在加載部門時也未被加載
- [綁定(排除=「僱員」)]屬性在控制器操作參數中,這沒有任何影響
- [Bind(Exclude =「Department.Employees 「)]相同
什麼工作,但我敢肯定,必須有一個更好的解決方案:
function _updateEmployee(employee) {
var newEmp = angular.copy(employee);
delete newEmp.department.employees;
return $http.put(employeesUrl, newEmp);
}
顯示您的EmployeeVM請 – Artiom 2015-04-01 13:06:05