ASP.Net MVC、WebAPI、AngularJS - 检查值是否存在于数据库中

ASP.Net MVC, WebAPI, AngularJS - Check if value exists in database

我在 ASP.net MVC 应用程序中使用 webapi 和 angularjs。一切正常,但在我的插入 (post) 方法中,我需要在插入之前检查数据库中是否存在值。我不确定应该去哪里。我排除了 webapi,因为 void 没有 return 值。合乎逻辑的地方似乎是控制器,但我找不到从插入控制器方法中调用 angular getEmployee(id) 方法的正确方法。任何帮助表示赞赏。

Angular 控制器 (post):

$scope.insertEmployee = function (employee) {
    employeeFactory.insertEmployee(employee)
        .success(function (emp) {
            $scope.employee = emp;
        })
        .error(function (error) {
            $scope.status = 'Unable to load employee data: ' + error.message;
        });
};

Angular 工厂 (post):

factory.insertEmployee = function (employee) {
    url = baseAddress + "employee/insert/";
    $http.post(url, employee).success(function (data) {
        alert("Saved Successfully!!");
    }).error(function (data) {
        $scope.error = "An Error has occured while saving employee! " + data;
    });
};

webapi 控制器post 方法:

    [Route("api/employee/insert/")]
    public void Post(Employee employee)
    {
        if (ModelState.IsValid)
        {
            context.Employee.Add(employee);
            context.SaveChanges();
        }
    }

Angular控制器(获取):

$scope.getEmployees = function (term) {
    employeeFactory.getEmployees(term)
        .success(function (data) {
            $scope.employees = data;
        })
        .error(function (error) {
            $scope.status = 'Unable to load employee data: ' + error.message;
        });
};

您的工厂与您的控制器不匹配。如果你想使用 employeeFactory.insertEmployee 中的 successerror,它需要 return 承诺:

factory.insertEmployee = function (employee) {
  url = baseAddress + "employee/insert/";
  return $http.post(url, employee);
};

那么你可以做

employeeFactory.insertEmployee(employee).success( ... )

现在要回答您的问题,您可以在 insertEmployee 中读取数据库以检查该值是否存在,然后再插入它。或者保存服务器调用并在插入请求期间进行检查:如果员工存在,return 错误或特定消息告诉客户端。

我建议在您的 web-api 服务器端执行此操作。您可以构造一个异常并抛出它。一些伪代码:

   [Route("api/employee/insert/")]
    public void Post(Employee employee)
    {
        if (ModelState.IsValid)
        {
            // verify doesn't already exist
            if(...item-already-exists...) {
               var resp = new HttpResponseMessage(HttpStatusCode.Conflict)
               {
                  Content = new StringContent("Employee already exists!")),
                  ReasonPhrase = "Employee already exists!"
               }
               throw new HttpResponseException(resp);
            }

            context.Employee.Add(employee);
            context.SaveChanges();
        }
    }

在 floribon 和 Nicholas Smith 的帮助下,我想出了一个解决方案,将错误冒泡到我的视图中,我将其显示在 div 元素中。这只是骨架,但这是一个开始。

我的 angular 控制器:

$scope.insertEmployee = function (employee) {
    employeeFactory.insertEmployee(employee)
        .success(function (data) {
            $scope.employee = data;
            $scope.status = 'The item was saved';
        })
        .error(function (error) {
            $scope.status = 'Unable to save the employee data: ' + error;
        });
};

我的angular工厂:

factory.insertEmployee = function (employee) {
    url = baseAddress + "employee/insert/";
    return $http.post(url, employee);
};

我的 webapi 控制器:

    [Route("api/employee/insert/")]
    public HttpResponseMessage Post(Employee employee)
    {
        HttpResponseMessage response;

        // check for the employee
        var employeeCheck = context.Employee
                        .Where(b => b.EmployeeNumber == employee.EmployeeNumber)
                        .FirstOrDefault();

        if (employeeCheck == null)
        {
            // save the item here
            response = Request.CreateResponse(HttpStatusCode.OK);
        }
        else
        {
            response = Request.CreateResponse(HttpStatusCode.Conflict, "The item already exists");
        }
        return response;
    }

结果是消息是 "Unable to save the employee data: The item already exists"。