【问题标题】:Error Duplicate Info on Insert ASPNET CORE插入 ASPNET CORE 时出现重复信息错误
【发布时间】:2017-09-13 15:47:15
【问题描述】:

当我添加一个员工时,我询问公司的数据,添加下一个员工再次询问我公司的数据并生成重复记录。如果这两名员工来自同一家公司,那应该是我的验证,这样我就不会重新注册公司?

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

}

公司表

如何验证信息不重复?

【问题讨论】:

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


【解决方案1】:

您可以尝试以下方法。基本上,如果已经存在,则需要将“公司”设置为 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);

【讨论】:

  • 但是当我将公司定义为null时,我没有引用该员工的公司,我需要保存信息,该员工属于该公司但不要再次添加公司,这将加倍
  • 所以分配现有公司而不是 null
【解决方案2】:

您可以使用抽象验证器。 模型是有效状态是配置您的验证规则。 示例

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多