1

插入:

[HttpPost]
public void InsertDirector(Director director)
{
    myConnection.Open();
    var query = "INSERT INTO dbo.AWD_Directors (AwardTitleId, PersonId, NameId,  DirectorSequence, IsOnBallot, Concatenation, WhoEntered, WhoChanged) VALUES (" + director.AwardTitleId + ", " + director.PersonId + ", " + director.NameId + ", " + director.DirectorSequence + ", " + director.IsOnBallot + ", '" + director.Concatenation + "', 0, 0)";
    var cmd = new SqlCommand(query, myConnection);
    cmd.ExecuteNonQuery();
    myConnection.Close();
}

更新:

[HttpPost]
public void UpdateDirector(Director director)
{
  myConnection.Open();
  var query = "UPDATE dbo.AWD_Directors SET NameId=" + director.NameId + ", DirectorSequence = " + director.DirectorSequence + ", IsOnBallot = " + director.IsOnBallot + ", Concatenation = '" + director.Concatenation + "' WHERE AwardTitleId = " + director.AwardTitleId + "AND PersonId = " + director.PersonId + " AND NameId = " + director.NameId;
  var cmd = new SqlCommand(query, myConnection);
  cmd.ExecuteNonQuery();
  myConnection.Close();
}

插入路线:

routes.MapHttpRoute(name: "InsertDirector", routeTemplate: "api/awards/directors", defaults: new
{
    controller = "Awards", action = "InsertDirector"
});

更新路线:

routes.MapHttpRoute(name: "UpdateDirector", routeTemplate: "api/awards/directors", defaults: new
{
    controller = "Awards",
    action = "UpdateDirector"
 });

我可以使用哪些命名约定来改进我所拥有的内容?

顺便说一句,不要介意内联 SQL。这将在以后更改。

4

2 回答 2

1

REST 的约定是我们使用 HttpMethods 进行 CRUD 操作选择:

  • GET - 读取操作(列表和 GetById)
  • POST - 插入
  • PUT - 更新
  • 删除 - 删除

详细描述:创建支持 CRUD 操作的 Web API

然后使用非常默认的路由设置(在此处查看更多信息:ASP.NET Web API 中的路由

routes.MapHttpRoute(
    name: "API Default",
    routeTemplate: "api/{controller}/{id}",   // the Director as controller
    defaults: new { id = RouteParameter.Optional }
);

所以,我们刚刚指示了 Web API 基础设施,如果有方法:

[HttpPost]
public void InsertDirector(Director director) ...

它将用于创建,并且使用的 HttpMethod 必须是POST

//[HttpPost]
[HttpPut]      // !! Attention, here is the difference
public void UpdateDirector(Director director)... 

UpdateDirector如果 HttpMethod是PUT

注意:因为在更新期间我们确实有现有产品的 ID,所以 Update 方法应该如下所示:

// the id parameter is a convention as well, 
// to be sure that we are updating existing item
// so this would be better
public void UpdateDirector(int id, Director director)... 
于 2013-09-12T03:21:31.777 回答
0

如果是插入/更新的情况,我假设您在某处会有一个 ID 字段(隐藏的 HTML)。您应该调用相同的方法,该方法的逻辑如下

如果 ID 为空或零。
如果 ID 为正数,则进行插入。更新 ID = html.ID

于 2013-09-11T17:45:59.223 回答