简体   繁体   English

SqlParameter在实体框架SqlQuery中返回null

[英]SqlParameter returns null in Entity Framework SqlQuery

I am materializing entities through a stored procedure in Entity Framework Code-First. 我正在通过Entity Framework Code-First中的存储过程来实现实体。 The Stored Procedure takes an int parameter and outputs both a selection of records and several output parameters. 存储过程采用一个int参数,并输出记录选择和多个输出参数。 For whatever reason, I am getting Null back on my output parameters while executing the Proc from SQL Management studio results in expected behavior; 无论出于何种原因,在从SQL Management Studio执行Proc时,我都会在输出参数上返回Null,这会导致预期的行为; all output parameters have values. 所有输出参数都有值。 My entities are being materialized, so at least that is working... 我的实体正在实现,因此至少可以正常工作...

EF Code EF代码

        SqlParameter DocsWithHits = new SqlParameter()
        {
            ParameterName = "DocumentsWithHits",
            Direction = System.Data.ParameterDirection.Output,
            Value = null,
            SqlDbType = System.Data.SqlDbType.Int
        };

        SqlParameter TotalGB = new SqlParameter()
        {
            ParameterName = "TotalGb",
            Direction = System.Data.ParameterDirection.Output,
            Value = null,
            SqlDbType = System.Data.SqlDbType.Float
        };

        ObservableCollection<SearchResult> ResultCollection;
        ResultCollection = new ObservableCollection<SearchResult>(db.Database.SqlQuery<SearchResult>(
            "exec ListSearchResultsWithTotals @SearchAnalysisID, @DocumentsWithHits, @RelatedDocuments, @TotalDocuments, @TotalGb, @DocumentsWithHitsNotExported, @RelatedDocumentsNotExported, @TotalDocumentsNotExported, @TotalGbNotExported",
            new SqlParameter
            {
                ParameterName = "SearchAnalysisID",
                Value = this.SearchAnalysisId
            },
            DocsWithHits,
            TotalGB));

SQL Profiler SQL事件探查器

The SQL that is generated from the SqlQuery method is below. 下面是从SqlQuery方法生成的SQL。 I captured it in Profiler. 我在Profiler中捕获了它。 When executed I get records and null output parameters. 执行后,我得到记录和空输出参数。

declare @p4 int
set @p4=NULL
declare @p5 float
exec sp_executesql N'exec ListSearchResultsWithTotals @SearchAnalysisID, @DocumentsWithHits, @TotalGb',N'@SearchAnalysisID int,@DocumentsWithHits int output,@TotalGb float output',@SearchAnalysisID=170,@DocumentsWithHits=@p4 output,@TotalGb=@p5 output
select @p4, @p5, @p6, @p7, @p8, @p9, @p10, @p11

Am I using SqlParameter wrong or what? 我使用SqlParameter错误还是什么?

You must use OUT keyword in SQL passed to SqlQuery (example here ). 您必须在传递给SqlQuery SQL中使用OUT关键字( 此处为示例)。 Also make sure that you are reading those parameters after you iterated or closed the main result set of the query (it should be done by ObservableCollection constructor). 还应确保在迭代或关闭查询的主要结果集之后读取这些参数(应由ObservableCollection构造函数完成)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM