2017-04-17 28 views
0

當我添加一個員工時,我詢問公司的數據,添加下一位員工再次詢問我公司的數據並生成重複記錄。如果這兩名員工來自同一家公司,應該是我的確認,以便我不重新註冊公司?錯誤插入ASPNET核心的重複信息

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

}

公司表 Database Duplicate Info

如何驗證不重複的信息?

+0

你似乎不有你'Employee'和'Company'實體之間的外鍵。 – Cameron

+0

http://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx –

回答

0

你可以嘗試下面的東西。基本上你需要將「公司」設置爲空,如果已經存在。

 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); 
+0

但是,當我將公司定義爲空時,我並不提及公司該員工,我需要保存信息,該員工屬於該公司,但不能再次添加公司,這將增加一倍 –

+0

因此,請指定現有公司而不是空值 – trigras

0

您可以使用抽象驗證器。 模型有效狀態配置了您的驗證規則。 例

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