2017-02-16 3 views
-3

새 직원을 만드는 동안 직원 이름 가용성을 확인하려고합니다. 삽입 된 직원 이름이 이미 사용 가능하면 사용자를 생성하는 동안 테이블이 이미 존재하고 그렇지 않으면 사용 가능한 메시지가 표시됩니다.

여기

이름을 이미 확인하는 방법

[Table("tblEmployee")] 
public class Employee 
{ 

    public int EmployeeID { get; set; } 
    [Required(ErrorMessage ="Name Cannot Be Empty")] 
    public string Name { get; set; } 

    [Required(ErrorMessage = "Name Cannot Be Empty")] 
    public string Gender { get; set; } 
    [Required(ErrorMessage = "Name Cannot Be Empty")] 
    public string City { get; set; } 
} 



아래는 아래



[HttpPost] 
    public ActionResult Create(Employee employee) 
    { 
     if (ModelState.IsValid) 
     { 
      if (employee.Name!=employee.Name) 
      { 
       db.Employees.Add(employee); 
       db.SaveChanges(); 
       return RedirectToAction("Index"); 
      } 
      else 
      { 
       ViewBag.errorMessage = "Name Already Available"; 
       return (ViewBag.errorMessage); 
      }   

     } 
     else 
     { 
      return View("Create"); 
     } 
    } 
@model Practise.Models.Employee 

@{ 
    ViewBag.Title = "Create"; 
} 
<h2>Create</h2> 

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken() 
    <div class="form-horizontal"> 
    <h4>Employee</h4> 
    <hr /> 
    @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 
    <div class="form-group"> 
     @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" }) 

     <div class="col-md-10"> 
      @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) 
      @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" }) 
     </div> 

     @ViewBag.errorMessage 
    </div> 

    <div class="form-group"> 
     @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 
      @Html.EditorFor(model => model.Gender, new { htmlAttributes = new { @class = "form-control" } }) 
      @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" }) 
     </div> 
    </div> 

    <div class="form-group"> 
     @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 
      @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } }) 
      @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" }) 
     </div> 
    </div> 
    <div class="form-group"> 
     <div class="col-md-offset-2 col-md-10"> 
      <input type="submit" value="Create" class="btn btn-default" /> 
     </div> 
    </div> 
</div> 
Create.cshtml

인가에는 EmployeeController에서 방법을 만들기가 내 직원 모델 클래스 당신은 자신과 동일한 직원의 이름을 비교하려고

employee.Name!=employee.Name 

:

}

+0

'employee.Name과 같아야 만들! = employee.Name' 이유는 무엇입니까 내 이름과 동일하지 내 이름? –

+1

'POST' 액션에서 라인 코드를 추가하여 모든 직원들이'employee.Name'에 의해 그것들을 찾도록해야합니다. 결과가 'null'이면 테이블에 추가 할 수 있습니다. 또한, @ TânNguyễn이 말한 것처럼,'employee.Name! = employee.Name'은 아마도 가장 쓸모없는 일일 것입니다. –

+2

대부분의 고용주는 조만간, 현실 세계의 많은 사람들이 같은 이름을 가질 수 있음을 깨닫게 될 것입니다 . 직원 이름을 고유 키로 사용하면 직원이 자신의 이름을 변경하도록 요청하면 불만을 토로하는 경향이 있습니다. 또한 두 사람이 정확히 같은 시간에 제출하면 어떻게 될지 고려해야합니다. 그들은 둘 다 복종한다. 두 수표는 모두 통과합니다. 두 개의 새 레코드가 만들어집니다. 이런! 적어도 *에서는 데이터베이스 수준에서 고유성을 강제해야하며 위반되는 고유성에 대처할 수있는 코드를 작성해야합니다. –

답변

0

귀하의 방법은

if (ModelState.IsValid) 
{ 
    // Check if employee with the same name already exists 
    var existingEmployee = db.Employees.FirstOrDefault(e => e.Name == employee.Name); 

    // No 
    if (existingEmployee == null) 
    { 
     db.Employees.Add(employee); 
     db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 
    // Yes 
    else 
    { 
     ViewBag.errorMessage = "Name not available"; 
     return (ViewBag.errorMessage); 
     }   
} 
+0

고맙습니다. – CrossWords

0

코드 행은 이해가되지 않습니다.

대신 같은 뭔가 이름으로 db.Employees을 검색한다 : "doesEployeeExist는"false 인 경우

var doesEployeeExist = db.Employees.Any(e => e.Name == employee.Name); 

, 당신은 이름을 사용하지 않을 것을 알고, 당신은을 만들 무료입니다 새로운.

그러나 특히 회사의 규모가 커질수록 사람들은 동일한 이름 (처음에는 &)을 사용하는 것이 가능하다는 사실을 알고 있어야합니다.

0

Any()Linq에 사용해보세요. 이처럼 :

// This will check if there is an existing name in your database 
bool IsEmployeeExist = db.Employees.Any(e => e.Name.Equals(employee.Name)); 

if(IsEmployeeExist){ 
    // Show Error Message 
} else { 
    // Do insert... 
} 

내가 같은 이름을 가질 수있는 사람들이 많이있을 것으로 확인하는 직원 이름이 너무 일반적이라고 생각하지만

.

관련 문제