c# - 如何检查列中的最新值并生成具有该特定值+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");
}
解决方案
如果您不想使用身份字段,则可以像这样获取当前的最高 ID:
SELECT MAX(ID) FROM dbo.Recipe
您可以在单独的查询中执行此操作,也可以将其嵌入到您的插入中:
INSERT INTO dbo.Recipe (Id, Name,...)
VALUES ((SELECT MAX(ID) + 1 FROM dbo.Recipe), @name, …)
如果您使用单独的查询,您应该使用事务和表锁,以防两个人同时尝试创建行。
推荐阅读
- typescript - 类型“未定义”不可分配给类型“T”
- rust - 使用 Pest.rs 如何管理以“\”结尾的多行语法?
- gnome - 从 gnome-extensions 运行 sudo 命令
- intellij-idea - 将代理配置从 WinSCP 导入 IntelliJ
- c - 重定向为输出时如何关闭 git bash?
- sql-server - SQL Server 查询以按年获取日期和命名列
- semantic-web - 以语义网三元组表示的煎饼配方
- javascript - 如何读取 ClientResult 的值
- python - 使用 Python 在图像 DWT 系数中嵌入文本
- spring - Spring安全动态角色权限角色和权限不起作用