返回EF Core Database.ExecuteSqlInterpolatedSync的存储过程值



我有一个C#方法,它调用一个执行insert语句的有效存储过程。如何在insert语句之后取回标识(主键(。

public async Task AddFileFolderStructure(int id, string folderName, string folderType)
{
var sproc_cmd = "dbo.AddFileFolderStructure";
await Database.ExecuteSqlInterpolatedAsync($"{sproc_cmd} {id}, {folderName}, {folderType}");
}

这是我修改的存储过程

ALTER PROCEDURE [dbo].[AddFileFolderStructure]
(@ParentId INT, 
@FolderName VARCHAR(255), 
@FolderType VARCHAR(255),
@id int OUTPUT)
AS
BEGIN
INSERT INTO [FileFolders] 
VALUES (@ParentId, @FolderName, @FolderType)
SELECT @id = SCOPE_IDENTITY();
RETURN @id
END

我还没有测试过,但它应该可以工作:

var output = new SqlParameter();
output.ParameterName = "@Id";
output.SqlDbType = SqlDbType.Int;
output.Direction = ParameterDirection.Output;
await Database.ExecuteSqlInterpolatedAsync("EXEC {0} @param1={1} OUT,@param2={2}, @param3={3} " sproc_cmd,output,folderName,folderType);

最新更新