當我添加一個員工時,我詢問公司的數據,添加下一位員工再次詢問我公司的數據並生成重複記錄。如果這兩名員工來自同一家公司,應該是我的確認,以便我不重新註冊公司?錯誤插入ASPNET核心的重複信息
public class Company
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(45)]
public string Code { get; set; }
[Required]
public string Name { get; set; }
public string BussinesName { get; set; }
public string WebAddress { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
public class Employee
{
[Key]
public int Id { get; set; }
public int EmployeeNumber { get; set; }
[Required]
public Company Company { get; set; }
[Required]
public bool Active { get; set; }
}
柱控制器
[HttpPost]
public IActionResult Post([FromBody]Employee data)
{
//Validamos
if(ModelState.IsValid){
//Agregamos registro
_context.Employee.Add(data);
return Ok(_context.SaveChanges());
}
return BadRequest(ModelState);
}
缺少公司數據的反應是:
{
"Person": [
"The Person field is required."
],
"Company.Code": [
"The Code field is required."
],
"Company.Name": [
"The Name field is required."
]
}
公司詳細
{
"Person": {
"lastNamePat": "Juan",
"lastNameMat": null,
"firstName": "Lopez"
},
"Company" :{
"Code": "XXX",
"Name": "test"
}
}
如何驗證不重複的信息?
你似乎不有你'Employee'和'Company'實體之間的外鍵。 – Cameron
http://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx –