繁体   English   中英

如何在 ASP.NET Core 3.0 的存储过程中添加参数

[英]How to add params in stored procedure in ASP.NET Core 3.0

我有这个存储过程:

CREATE PROCEDURE AddReserv
    @Place int,
    @StartDate datetime,
    @EndDate datetime
AS
BEGIN
    INSERT INTO [dbo].Reserv(UserId, Place,  StartDate, EndDate)
    VALUES (1, @Place, @StartDate, @EndDate)
END

从 post 方法中的 controller 开始,我想在表中添加一条新记录。 我不知道如何将参数传递给存储过程。

我在 controller 中的代码:

// POST: api/CreateReserv
[HttpPost]
public void Post(string value)
{
    using (var connection = _db.Database.GetDbConnection())
    {
        connection.Open();

        using (var command = connection.CreateCommand())
        {
            command.CommandType = System.Data.CommandType.StoredProcedure;
            command.CommandText = "AddReserv";

            //How to add params?
            /*
                    @Place int
                    @StartDate datetime
                    @EndDate datetime
            */

            command.ExecuteNonQuery();
        }
    }
}

您可以使用command.Parameters.Add添加参数,如下所示。

请确保您已安装NuGet package System.Data.SqlClient

using (var command = connection.CreateCommand())
{
    command.CommandType = System.Data.CommandType.StoredProcedure;
    command.CommandText = "AddReserv";
    
    command.Parameters.Add("@Place", SqlDbType.Int).Value = place;
    command.Parameters.Add("@StartDate", SqlDbType.DateTime).Value = startDate;
    command.Parameters.Add("@EndDate", SqlDbType.DateTime).Value = endDate;
    
    command.ExecuteNonQuery();     
}

用@Karan 的一些代码更新了我的答案(这应该是正确的答案)

....

  using var connection = _db.Database.GetDbConnection();
  connection.Open();

  using var command = new SqlCommand("AddReserv", connection)
  {
    CommandType = CommandType.StoredProcedure
  };

  command.Parameters.Add("@Place", SqlDbType.Int).Value = place;
  command.Parameters.Add("@StartDate", SqlDbType.DateTime).Value = startDate;
  command.Parameters.Add("@EndDate", SqlDbType.DateTime).Value = endDate;
  
  command.ExecuteNonQuery();

进一步的改进将是使用代码的异步版本。 注意:当您的代码完成后,如果发布 JSON,请不要忘记 [FromBody](有关此内容的更多信息: https://stackoverflow.com/a/63349923/14072498 )。

[HttpPost]
public async Task<IActionResult> Post(string value)
{
  await using var connection = _db.Database.GetDbConnection();
  await connection.OpenAsync();

  await using var command = new SqlCommand("AddReserv", connection)
  {
    CommandType = CommandType.StoredProcedure
  };

  command.Parameters.Add("@Place", SqlDbType.Int).Value = place;
  command.Parameters.Add("@StartDate", SqlDbType.DateTime).Value = startDate;
  command.Parameters.Add("@EndDate", SqlDbType.DateTime).Value = endDate;

  await command.ExecuteNonQueryAsync();

  ....
}

不确定 _db 是什么类型,如果

_db.Database.GetDbConnection()

有一个异步版本,也可以使用它。

暂无
暂无

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

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