简体   繁体   English

ASP.NET Web API控制器更新行

[英]ASP.NET Web API Controller Update Row

I'm having issues figuring out how to update just a single row in a controller in ASP.NET. 我在弄清楚如何在ASP.NET中的控制器中仅更新一行时遇到问题。 I am trying to send a post request to the Web API I created and the request goes through but instead of updating only one row, it updates all rows (all rows in the column goal) in the table I am trying to manipulate in my SQL database. 我试图将发布请求发送到我创建的Web API,请求通过了,但是它不更新仅一行,而是更新了我试图在SQL中操作的表中的所有行(列目标中的所有行)数据库。 Any help with this problem would be appreciated. 任何有关此问题的帮助将不胜感激。 I am sending the post request using the $http service in AngularJS. 我正在使用AngularJS中的$ http服务发送发布请求。

ASP.NET C# ASP.NET C#

    public class patient_goalsController : ApiController
    { 
        .
        .
        .

        //POST: api/goals/update/1
        [Route("Api/goals/update/{id}")]
        public void UpdatePatientGoal(int id, patient_goals patient_goals)
        {
            var goals = (from p_goal in db.patient_goals
                        where patient_goals.id == id
                        select p_goal);
            foreach(patient_goals row in goals)
            {
                row.goal = patient_goals.goal;
            }


        }

        .
        .
        .

   }

AngularJS AngularJS

$scope.updateGoal = function(goal){
goal.editing = false;
console.log(goal.id);
var data = {"id": goal.id, "goal": goal.goal}
$http({
  method: "POST",
  url: urlBase + "/goals/update/" + goal.id,
  data: data,
}).then(function error(response) {
  $scope.error = response.statusText;
  console.log(response.statusText);
});

DB D B

id (int)
goal (text)

Just find the single connected entity you want, make the edits and then save your changes. 只需找到所需的单个连接实体,进行编辑,然后保存更改即可。

[Route("Api/goals/update/{id}")]
 public void UpdatePatientGoal(int id, patient_goals)
 {
      var goal =  db.patient_goals.FirstOrDefault(x => x.id == id);

      if(goal != null)
      {
          goal.goal  = patient_goals.goal;
          db.SaveChanges();
      }
  }

I don't really know the details of your database schema, but it looks like your where -clause is incorrect. 我真的不知道你的数据库架构的细节,但它看起来像你的where -clause不正确。 Rather than comparing to patient_goals.id , you would be comparing to p_goal : 与其将其与patient_goals.id进行比较, p_goal将其与p_goal进行比较:

           var goals = (from p_goal in db.patient_goals
                        where p_goal.id == id
                        select p_goal);

Otherwise, you are simply comparing values from your parameter list. 否则,您只是在比较参数列表中的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM