首页 > 解决方案 > 如何检查列中的最新值并生成具有该特定值+1的新行?

问题描述

我发现很难弄清楚如何为 API 创建的每个配方自动生成列 ID。此时,如果我想在Recipe表中新建一行,我必须自己插入一个ID,否则它只会被赋值为0。我正在寻找一种方法来检查最新的ID已经存在于数据库,当创建新条目时,其 ID 将为最新 ID + 1。

API中的RecipeController

        [Route("v1/recipe")]
    [HttpPost()]
    public IActionResult CreateList([FromBody]Recipe recipe)
    {
        try
        {
            if (recipe == null) throw new ArgumentException("No data specified");
            //if (recipe.Name == null) throw new ArgumentException("No name specified");

            using (var con = _connFactory())
            {
                con.Open();
                con.Execute(@"INSERT INTO dbo.Recipe (Id, Name, RecipeLink, Category1Id ,Category2Id, Category3Id, Category4Id, RecipeById,
                            TotalTime, TotalTimeUnitId, ActiveTime, ActivetimeUnitId, Instructions, SourceKey, RecipeBy, InsertedAtUtc, IsVerified, NumPersons) 
                            VALUES (@id, @name, @recipeLink, @category1Id, @category2Id, @category3Id, @category4Id, @recipeById,
                            @totalTime, @totalTimeUnitId, @activeTime, @activeTimeUnitId, @instructions, @sourceKey, @recipeBy, getutcdate(), @isVerified, @numPersons)",
                            new
                            {
                                recipe.id,
                                recipe.name,
                                recipe.recipeLink,
                                recipe.category1Id,
                                recipe.category2Id,
                                recipe.category3Id,
                                recipe.category4Id,
                                recipe.recipeById,
                                recipe.totalTime,
                                recipe.totalTimeUnitId,
                                recipe.activeTime,
                                recipe.activeTimeUnitId,
                                recipe.instructions,
                                recipe.sourceKey,
                                recipe.recipeBy,
                                recipe.isVerified,
                                recipe.numPersons
                            });
            }
            return Ok(recipe);
        }
        catch (Exception exc)
        {
            return BadRequest();
        }

来自 MVC 的RecipeController

        [HttpPost]
    public ActionResult CreateOrEdit(Recipe recipe)
    {
        if (recipe.id == 0)
        {
            HttpResponseMessage response = GlobalVariables.client.PostAsJsonAsync("", recipe).Result;
        }
        else
        {
            HttpResponseMessage response = GlobalVariables.client.PutAsJsonAsync(recipe.id.ToString(), recipe).Result;
        }
        return RedirectToAction("Index");
    }

标签: c#sqlasp.netsql-server

解决方案


如果您不想使用身份字段,则可以像这样获取当前的最高 ID:

SELECT MAX(ID) FROM dbo.Recipe

您可以在单独的查询中执行此操作,也可以将其嵌入到您的插入中:

INSERT INTO dbo.Recipe (Id, Name,...)
VALUES ((SELECT MAX(ID) + 1 FROM dbo.Recipe), @name, …)

如果您使用单独的查询,您应该使用事务和表锁,以防两个人同时尝试创建行。


推荐阅读