对于实体框架中的所有情况,存储过程返回 -1 [英] Stored Procedure return -1 for all cases in entity framework

查看:20
本文介绍了对于实体框架中的所有情况,存储过程返回 -1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CREATE PROC spIsValidUser
     @UserName varchar(50),
     @Password varchar(50) 
AS
    IF  Exists(SELECT * FROM Users where UserName=@UserName and Password=@Password)
    BEGIN
        return 0

    END
    ELSE
    BEGIN
        return 1
    END
 GO

我创建了这个 Stored Procedure 并尝试使用实体框架调用这个 Stored Procedure.下面是用 C# 编写的代码.

I have created this Stored Procedure and tring to call this Stored Procedure using entity framework. Below is code in written in C#.

MyBusEntities db = new MyBusEntities();
int empQuery = db.spIsValidUser("abc", "abc@123");

spIsValidUser Stored Procedure 在所有情况下都返回 -1.请让我知道错误.

spIsValidUser Stored Procedure return -1 in all case. Please let me know error.

EDIT - 根据给出的答案,不使用存储过程返回语句,因为实体框架不能支持存储过程立即返回标量值..让我知道如何从存储过程?

EDIT - According to given answer, Store procedure is not used return statement because Entity Framework cannot support Stored Procedure Return scalar values out of the box..Let me know how can I send scalar data from Stored Procedure?

推荐答案

您的存储过程当前返回一个标量值.使用以下步骤解决此问题:

Your stored procedure is currently returns a scalar value. Use the following steps to solve this issue:

  • 像这样改变你的存储过程(不要在存储过程中使用关键字return来返回值,实体框架不支持存储过程返回标量 开箱即用的值.但有一个解决方法):

  • Change your stored procedure like this (Don't use the keyword return in the stored procedure to return the value, Entity Framework cannot support Stored Procedure Return scalar values out of the box. BUT there is a work around):

ALTER PROC spIsValidUser
@UserName varchar(50),
@Password varchar(50) 
AS
SELECT Count(*) FROM Users where UserName= @UserName and Password= @Password
return

  • 您需要将存储过程作为 Function 导入.右键单击实体模型的工作区,然后选择 Add ->函数导入.

  • You need to Import the stored procedure as a Function. Right-click on the workspace area of your Entity model and choose Add -> Function Import.

    Add Function Import 对话框中,输入您希望在模型中引用您的存储过程的名称,从下拉列表中选择您的过程,然后选择返回值过程的标量.

    In the Add Function Import dialog, enter the name you want your stored procedure to be referred to in your model, choose your procedure from the drop down list, and choose the return value of the procedure to be Scalar.

    最后像这样写代码:

    MyBusEntities db = new MyBusEntities();
    System.Nullable<int> empQuery = db.spIsValidUser("abc", "abc@123").SingleOrDefault().Value;
    MessageBox.Show(empQuery.ToString());// show 1 if Exist and 0 if not Exist
    

  • 我认为对存储过程返回值的支持取决于实体框架的版本.此外,实体框架没有丰富的存储过程支持,因为它是一个 ORM,而不是 SQL 替代品.

    I think support of stored procedure return values depends on version of Entity framework. Also Entity Framework doesn't have rich stored procedure support because its an ORM, not a SQL replacement.

    这篇关于对于实体框架中的所有情况,存储过程返回 -1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆