首页 > 解决方案 > 创建对象并将其传递到数据库后未显示 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 个配方,这可能是一个问题。

标签: c#sql-serverjson.net

解决方案


您可以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-ServerSequenceIDENTITY. 使用select max()可以生成重复项


推荐阅读