When I add an employee, I ask for the data of the company, adding the next employee asks me again the data of the company and generates duplicate records. If the two employees are from the same company as it should be my validation so that I do not re-register the company?
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; }
}
POST CONTROLLER
[HttpPost]
public IActionResult Post([FromBody]Employee data)
{
//Validamos
if(ModelState.IsValid){
//Agregamos registro
_context.Employee.Add(data);
return Ok(_context.SaveChanges());
}
return BadRequest(ModelState);
}
The response to missing company data is:
{
"Person": [
"The Person field is required."
],
"Company.Code": [
"The Code field is required."
],
"Company.Name": [
"The Name field is required."
]
}
Company Details
{
"Person": {
"lastNamePat": "Juan",
"lastNameMat": null,
"firstName": "Lopez"
},
"Company" :{
"Code": "XXX",
"Name": "test"
}
}
How to validate not duplicate information?
You can use Abstract validator. Model Is valid state is configured your validation rule. Example
RuleFor(c => c.ModuleId)
.NotEmpty()
.WithMessage("Module id is required.")
.Must(BeAnExistingModule)
.WithMessage("Module does not exist.");
private bool BeAnExistingModule(AddVersion cmd, Guid moduleId)
{
return _moduleRules.DoesModuleExist(cmd.SiteId, moduleId);
}