EF6 CodeFirst - 处理输出参数

EF6 CodeFirst - Dealing with OUTPUT parameters

我正在尝试使用 EF6/CodeFirst 的存储过程。这个 SP returns 几个值通过 OUTPUT 参数。我在 other places 中看到这可能是不可能的,但这篇文章已经很老了,只是想知道现在是否已经解决了。

使用 RAW Sql(在 SSMS 中)执行时我的 SP 是这样工作的;

    declare @p10 int
    declare @p11 uniqueidentifier
    set @p10=NULL
    set @p11=NULL
    exec dbo.uspTestStoredProc @id = 2021, @name=N'qa1231321asda.txt', 
         @documentId=@p10 OUTPUT,@documentStreamId=@p11 output
    select @p10,@p11

这个正确打印出 documentId (p10) 和 documentStreamId (p11)

但是,当通过 EF 执行时,这两个 OUTPUT 参数都为空。我在下面包含了 .Net 代码和通过 EF 生成的 SQL 以供进一步调查。

.网络代码

var sqlString = "exec dbo.uspTestStoredProc @id,@name,@documentId,@documentStreamId";
var paramCollection = new List<Object>
                {
                    new SqlParameter("id", 81),
                    new SqlParameter("name", "qa1231321asda2.txt"),
                };

                var paramDocId = new SqlParameter
                {
                     ParameterName = "@documentId",
                     SqlDbType = SqlDbType.Int,
                     Value = 0,
                     Direction = ParameterDirection.Output
                };
                paramCollection.Add(paramDocId);

                var paramStreamId = new SqlParameter
                {
                    ParameterName = "@documentStreamId",
                    SqlDbType = SqlDbType.UniqueIdentifier,
                    Value = DBNull.Value,
                    Direction = ParameterDirection.Output
                };

paramCollection.Add(paramStreamId);

_context.Database.ExecuteSqlCommand(sqlString, paramCollection.ToArray());

var docId = (int) paramDocId.Value; //Fails because paramDocId is DBNull

SQL 由 EF

生成
    declare @p10 int
    declare @p11 uniqueidentifier
    set @p10=NULL
    set @p11=NULL
    exec sp_executesql N'exec dbo.uspTestStoredProc @id,@name,@documentId,@documentStreamId', 
    N'@id int,@name nvarchar(45), @documentId int output,@documentStreamId uniqueidentifier output',
    @id=81,@name=N'qa1231321asda2.txt',@documentId=@p10 output,@documentStreamId=@p11 output
    select @p10, @p11

现在@p10 和@p11 returns NULL。

我正在尝试找出以下内容

  1. EF6/CodeFirst 可以支持存储过程中的 OUTPUT 参数吗?
  2. 如果是这样,我需要做哪些不同的事情?
  3. 如果没有,知道该功能何时可用吗?

非常感谢。

我想我终于找到了答案。诀窍在于您传递给命令的 sqlString。

    var sqlString = "exec dbo.uspTestStoredProc @id,@name,
                     @documentId OUT,@documentStreamId OUT";

注意2个输出参数后的关键字'OUT'。它可以解决问题。当然你还需要在添加参数时指定适当的SQL参数选项,如ParameterDirection.Output。