Error Duplicate Info on Insert ASPNET CORE

asp.net-core c# core entity-framework-core mysql

Question

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"
}

}

Company Table Database Duplicate Info

How to validate not duplicate information?

1
0
4/17/2017 11:54:38 PM

Popular Answer

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);
}
0
10/23/2018 12:52:10 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow