我正在尝试从我的数据库过程中检索数据,但我不确定为什么我应该返回值为1或0时返回-1。我觉得一切都正确传递,程序运行良好。但我可能是错的。
我将类型为“Status”的对象传递给我的数据库过程db.proc_CsStatus和db.proc_GhStatus。在调试器期间,虽然我得到“r”值为-1。
我的控制器:
public ActionResult Index()
{
ViewBag.CsStatus = GhCsStatusProvider.GetCsStatus();
ViewBag.GhStatus = GhCsStatusProvider.GetGhStatus();
return View();
}
我的提供商有以下两个功能:
public static int GetGhStatus()
{
using (Entities db = new Entities())
{
System.Data.Objects.ObjectParameter s = new System.Data.Objects.ObjectParameter("Status", typeof(int));
int r = db.proc_CsStatus(120, s);
return r;
}
}
public static int GetCsStatus()
{
using (Entities db = new Entities())
{
System.Data.Objects.ObjectParameter s = new System.Data.Objects.ObjectParameter("Status", typeof(int));
int r = db.proc_CsStatus(120, s);
return r;
}
}
以下是我的数据库程序:
USE [DATABASE_GH]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[proc_GhStatus]
-- Add the parameters for the stored procedure here
@TimeLimit Int,
@Status Int OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
-- Declare variables.
DECLARE @LastUpdate Int
-- Calculate the LastUpdate.
SELECT @LastUpdate = DATEDIFF(second, Timestamp, CURRENT_TIMESTAMP)
FROM Heartbeat
WHERE Id=2
-- Compare it to the TimeLimit.
IF @LastUpdate > @TimeLimit SELECT @Status = 0
ELSE SELECT @Status = 1
END
GO
USE [DATABASE_CS]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[proc_CsStatus]
-- Add the parameters for the stored procedure here
@TimeLimit Int,
@Status Int OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
-- Declare variables.
DECLARE @LastUpdate Int
-- Calculate the LastUpdate.
SELECT @LastUpdate = DATEDIFF(second, Timestamp, CURRENT_TIMESTAMP)
FROM Heartbeat
WHERE Id=1
-- Compare it to the TimeLimit.
IF @LastUpdate > @TimeLimit SELECT @Status = 0
ELSE SELECT @Status = 1
END
GO
答案 0 :(得分:1)
可能的问题是EF中导入的SP不会被告知返回值。要检查以下内容:
答案 1 :(得分:1)
在存储过程中,您不会返回状态。因此,您无法在下面的代码中设置状态。
int r = db.proc_CsStatus(120, s);
这只会返回存储过程执行的状态。 -1表示存储过程执行中存在一些错误。最简单的方法是删除out参数并从sp返回@status。然后,您应该能够以您的方式检索值。
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
-- Declare variables.
DECLARE @LastUpdate Int
-- Calculate the LastUpdate.
SELECT @LastUpdate = DATEDIFF(second, Timestamp, CURRENT_TIMESTAMP)
FROM Heartbeat
WHERE Id=1
-- Compare it to the TimeLimit.
IF @LastUpdate > @TimeLimit SELECT @Status = 0
ELSE SELECT @Status = 1
// Below line shoud be added.
RETURN @Status
还要确保在DBModel中设置正确的返回类型,如其他答案中所述。