插入ASPNET CORE时出现重复信息错误

时间:2017-04-17 23:54:38

标签: c# mysql asp.net-core entity-framework-core core

当我添加员工时,我要求公司的数据,添加下一位员工再次询问公司的数据并生成重复记录。如果这两名员工来自同一家公司,那么我应该进行验证,以便我不会重新注册该公司?

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

}

公司表 Database Duplicate Info

如何验证不重复的信息?

2 个答案:

答案 0 :(得分:0)

您可以尝试以下内容。基本上,如果已经存在,则需要将“Company”设置为null。

        if (ModelState.IsValid)
        {
            try
            {
                if (data != null && data.Company != null)
                {
                    if (_context.Employee.Company.Any(x => x.Code == data.Company.Code))
                    {
                        data.Company = null;
                        _context.Employee.Add(data);
                    }
                    else
                    {
                        _context.Employee.Add(data);
                    }
                }

                return Ok(_context.SaveChanges());
            }
            catch (Exception ex)
            {
            }
        }

        return BadRequest(ModelState);

答案 1 :(得分:0)

您可以使用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);
}