使用SQL查询在数据库中创建新条目时添加(最新添加的Id + 1)

Que*_*eme 1 c# sql-server asp.net-core

注意:我知道之前已经问过这个问题,对于这样一个愚蠢的重新发布,我很抱歉。但是,我找到的所有解决方案都没有真正帮助过我。我可能看错了地方 - 对不起!

是的,所以我试图Releases在我的数据库的表中添加一个新条目。下面显示了我的代码的样子。

[HttpPost]
public IActionResult Create(Release release)
{
    var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
    string connectionString = Configuration["ConnectionStrings:DefaultConnection"];
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        string sql = $"Insert Into Releases (Id, Name, StartDate, EndDate, OwnerId) Values ('(SELECT MAX(Id) + 1 FROM dbo.Releases)', '{release.Name}','{release.StartDate}','{release.EndDate}','{userId}')";

        using (SqlCommand command = new SqlCommand(sql, connection))
        {
            command.CommandType = CommandType.Text;

            connection.Open();
            command.ExecuteNonQuery();
            connection.Close();
        }
    }

    return View();
}
Run Code Online (Sandbox Code Playgroud)

在我的代码片段中,我使用SELECT MAX(Id) + 1以插入具有 column Id+ 1值的新条目最新条目。这以前对我有用,但现在由于某种原因,我收到以下错误:

System.Data.SqlClient.SqlException: '将 varchar 值 '(SELECT MAX(Id) + 1 FROM dbo.Releases)' 转换为数据类型 int 时转换失败。

虽然这个解决方案可能不是很理想 - 我正在为我的问题寻找合适的解决方案。

Joh*_*lay 6

回答您的问题时'(SELECT MAX(Id) + 1 FROM dbo.Releases)'不应用引号括起来;(SELECT MAX(Id) + 1 FROM dbo.Releases)将返回您的id列所需的整数值。

但是,您确实应该为您的 id使用自动递增列,因为同时请求可能会尝试两次插入相同的 id。

您还应该使用参数化查询而不是字符串插值,因为这会向 SQL 注入开放您的数据库。