c# - 创建对象并将其传递到数据库后未显示 ID 变量
问题描述
我已经完成了一个 POST 方法,它接受对象Recipe
并使用 Dapper 在数据库中插入其值。我编写了 SQL 查询,以便在插入新条目时,ID 值将自动生成为:数据库中的最大现有值 + 1。请参见下面的代码:
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, ServingsUnitId, ServingsUnitOrig)
VALUES ((SELECT MAX(ID) + 1 FROM dbo.Recipe), @name, @recipeLink, @category1Id, @category2Id, @category3Id, @category4Id, @recipeById,
@totalTime, @totalTimeUnitId, @activeTime, @activeTimeUnitId, @instructions, @sourceKey, @recipeBy, getutcdate(), @isVerified, @numPersons, @servingsUnitId, @servingsUnitOrig)",
new
{
...
...
});
}
当我使用 Postman 向 API 发送请求时,返回的结果将是新创建的已传递给数据库的对象。但是,由于创建我的 ID 的方式,返回的 JSON 看起来像这样:
{
"id": 0,
"name": "Test Recipe2",
"recipeLink": "testlink",
"category1Id": 7757,
...
"servingsUnitId": 3,
"servingsUnitOrig": null
}
如您所见,ID 为 0。但如果我尝试在此之后获取对象,则 ID 将设置为正确的 ID,即从(SELECT MAX(ID) + 1 FROM dbo.Recipe)
.
有什么方法可以让 API 在执行后返回正确的 ID INSERT INTO
?或者我应该如何改变自动生成背后的逻辑来实现这一点?
如果我能够直接获取 ID 的值,它将非常方便,因为现在我已经创建了一个方法来返回创建的最新配方的 ID。但是,如果在短时间内创建了 2 个配方,这可能是一个问题。
解决方案
您可以return
使用Id
并使用ExecuteScalar
来获取它。在执行语句declare
& 生成下一个 Id 和结束select the NewId value
using (var con = _connFactory())
{
con.Open();
var addedId = con.ExecuteScalar(@"DECLARE @NewId INT = (SELECT ISNULL(MAX(ID),0) + 1 FROM dbo.Recipe);INSERT INTO dbo.Recipe (Id, Name, RecipeLink, Category1Id ,Category2Id, Category3Id, Category4Id, RecipeById,
TotalTime, TotalTimeUnitId, ActiveTime, ActivetimeUnitId, Instructions, SourceKey, RecipeBy, InsertedAtUtc, IsVerified, NumPersons, ServingsUnitId, ServingsUnitOrig)
VALUES (@NewId, @name, @recipeLink, @category1Id, @category2Id, @category3Id, @category4Id, @recipeById,
@totalTime, @totalTimeUnitId, @activeTime, @activeTimeUnitId, @instructions, @sourceKey, @recipeBy, getutcdate(), @isVerified, @numPersons, @servingsUnitId, @servingsUnitOrig); SELECT @NewId",
new
{
...
...
});
//use addedId here...
}
我强烈建议您更改 Id 行为以使用 SQL-ServerSequence
或IDENTITY
. 使用select max()
可以生成重复项
推荐阅读
- python - 在 Ubuntu 16.04 (AWS EC2) 上损坏了 python 依赖项
- c++ - 如何使用 ISpLexicon::GetWords 获取单词列表?
- python - 用“with语句”关闭psyopg2中的连接的正确方法是什么?
- c# - 如何从列表中删除生成的标签
- c++ - 无法使用构造函数为类函数赋值
- c# - 从 System.IO.Abstractions 抛出 UnauthorizedAccessException
- apache-kafka - Openwhisk - 订阅队列
- kubernetes - 根据标签更新多个 pod
- android - 如何自动化一个特定的过程,比如每天在安卓设备上打开一个网站?
- android - 如何修复条形码扫描应用程序中的错误,发出网络请求时崩溃