Dapper-SQL Server生成的返回GUID

Dapper-SQL Server生成的返回GUID,dapper,Dapper,S/O上与插入后返回值相关的所有简洁的帖子似乎只与标识值相关。我试图将这些答案中的逻辑应用到我的问题上,但它不起作用 我想返回SQL Server生成的GUID,该GUID不是标识字段。这是我的代码: public bool Insert(Record record) { SqlConnection connection = new SqlConnection(_configuration.GetConnectionString("Production")); connectio

S/O上与插入后返回值相关的所有简洁的帖子似乎只与标识值相关。我试图将这些答案中的逻辑应用到我的问题上,但它不起作用

我想返回SQL Server生成的GUID,该GUID不是标识字段。这是我的代码:

public bool Insert(Record record)
{
    SqlConnection connection = new SqlConnection(_configuration.GetConnectionString("Production"));
    connection.Open();
    using (connection)
    {
        string query = "DECLARE @RSGUID uniqueidentifier SET @RSGUID = NEWID(); INSERT INTO [dbo].[Table] ([Result], [ResultSetKey]) VALUES (@Result, @RSGUID); SELECT @RSGUID";
        // it's this next line that I'm confused on:
        var resultSetKey = connection.Query<string>(query, @RSGUID).Single();
        return connection.Execute(query, record) > 0;
    }
}
public bool Insert(记录)
{
SqlConnection=newsqlconnection(_configuration.GetConnectionString(“Production”);
connection.Open();
使用(连接)
{
string query=“DECLARE@RSGUID uniqueidentifier SET@RSGUID=NEWID();插入[dbo].[Table]([Result],[ResultSetKey])值(@Result,@RSGUID);选择@RSGUID”;
//下一行我很困惑:
var resultSetKey=connection.Query(Query,@RSGUID.Single();
返回连接。执行(查询、记录)>0;
}
}

我知道
var resultsSetKey
行不正确,这就是我需要帮助的地方。如何将SQL Server生成的GUID获取到变量中?

我现在无法测试,但这应该可以:

public bool Insert(Record record)
{
    using (var connection = new SqlConnection(_configuration.GetConnectionString("Production"))
    {
        string query = "DECLARE @RSGUID uniqueidentifier; SET @RSGUID = NEWID(); INSERT INTO [dbo].[Table] ([Result], [ResultSetKey]) VALUES (@Result, @RSGUID); SELECT @RSGUID";
        var resultSetKey = connection.ExecuteScalar<string>(query).SingleOrDefault();
        return !String.IsNullOrEmpty(resultSetKey);
    }
}
public bool Insert(记录)
{
使用(var connection=newsqlconnection(_configuration.GetConnectionString(“生产”))
{
string query=“DECLARE@RSGUID uniqueidentifier;SET@RSGUID=NEWID();插入[dbo].[Table]([Result],[ResultSetKey])值(@Result,@RSGUID);选择@RSGUID”;
var resultSetKey=connection.ExecuteScalar(query.SingleOrDefault();
return!String.IsNullOrEmpty(resultSetKey);
}
}
您可以按照此处的教程使用Dapper获得kickstart:


但老实说,你到底想做什么还不清楚。你在T-SQL代码中使用的@Result变量是什么?

是的,这里肯定有一个问题,可能是b/c,我也不完全理解Dapper中发生了什么,对不起,我应该更清楚我在这里做什么。
@Result
正在通过d作为用户在网页上以表单形式输入的值。因此,使用您的代码,我现在得到了错误:必须声明标量变量
@Result
。但是如果我没有在SQL语句的开头声明
@RSGUID
,而只是以INSERT INTO开始,则
@Result
将填充上面提到的Javascript值。现在我更困惑了……。我需要能够正确地传递
@Result
,并将GUID返回给我。谢谢你的帮助,但不管怎样,我还是走了另一条路。我想我太困惑这个问题了。