为什么Entity Framework调用我的存储过程但返回不正确的值?

时间:2021-02-10 02:06:16

I have a stored procedure that simply returns the total number of records divided by whatever value is passed in. This is to aid in pagination on a website.

我有一个存储过程,只返回记录总数除以传入的任何值。这是为了帮助网站上的分页。

However, I am using the entity framework to bind to that stored procedure and it's returning -1 for all calls to it. When I interrogate the stored procedure using SQL Management Studio, it comes back with the correct value.

但是,我使用实体框架绑定到该存储过程,它为所有调用返回-1。当我使用SQL Management Studio查询存储过程时,它返回正确的值。

My stored procedure looks like this:

我的存储过程如下所示:

CREATE PROCEDURE [dbo].[GetAuditRecordPageCount]
@Count INTEGER
AS
RETURN ((SELECT COUNT(Id) FROM AuditRecords) / @Count) + 1

And my call to the entity framework in C# is this:

我在C#中对实体框架的调用是这样的:

int pageCount;
using (Entities entities = new Entities())
{
    pageCount = entities.GetAuditRecordPageCount(count);
}

Am I correct in writing the C# code this way?

我这样编写C#代码是否正确?

As per a request in the comments, the SQL generated by EF is:

根据注释中的请求,EF生成的SQL是:

exec [dbo].[GetAuditRecordPageCount] @Count=100

1 个解决方案

#1


3  

Did you tried that? http://www.devtoolshed.com/using-stored-procedures-entity-framework-scalar-return-values

你试过那个吗? http://www.devtoolshed.com/using-stored-procedures-entity-framework-scalar-return-values

I think your procedure will look like this:

我认为你的程序看起来像这样:

CREATE PROCEDURE [dbo].[GetAuditRecordPageCount]
@Count INTEGER
AS
declare @retVal int
set @retVal = ((SELECT COUNT(Id) FROM AuditRecords) / @Count) + 1
select @retVal

And in the c# code:

并在c#代码中:

int? pageCount;
using (Entities entities = new Entities())
{
   pageCount = entities.GetAuditRecordPageCount(count).SingleOrDefault();

   if (pageCount.HasValue)
   {
      //do something here
   }
   else
   {

   }
}

Don't forget to put "Scalars: Int32" in edit function Import screen.

不要忘记在编辑功能导入屏幕中放置“Scalars:Int32”。

#1


3  

Did you tried that? http://www.devtoolshed.com/using-stored-procedures-entity-framework-scalar-return-values

你试过那个吗? http://www.devtoolshed.com/using-stored-procedures-entity-framework-scalar-return-values

I think your procedure will look like this:

我认为你的程序看起来像这样:

CREATE PROCEDURE [dbo].[GetAuditRecordPageCount]
@Count INTEGER
AS
declare @retVal int
set @retVal = ((SELECT COUNT(Id) FROM AuditRecords) / @Count) + 1
select @retVal

And in the c# code:

并在c#代码中:

int? pageCount;
using (Entities entities = new Entities())
{
   pageCount = entities.GetAuditRecordPageCount(count).SingleOrDefault();

   if (pageCount.HasValue)
   {
      //do something here
   }
   else
   {

   }
}

Don't forget to put "Scalars: Int32" in edit function Import screen.

不要忘记在编辑功能导入屏幕中放置“Scalars:Int32”。