錯誤重複信息插入ASPNET核心

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

當我添加員工時,我要求公司的數據,添加下一位員工再次詢問公司的數據並生成重複記錄。如果這兩名員工來自同一家公司,那麼我應該進行驗證,以便我不重新註冊公司?

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控制器

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

}

公司表數據庫重複信息

如何驗證不重複的信息?

熱門答案

您可以使用Abstract驗證器。模型是否為有效狀態配置了驗證規則。例

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);
}


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow