Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

c# - Stored Procedure return -1 for all cases in entity framework

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

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 return -1 in all case. Please let me know error.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

  • 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
    
  • 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.

  • 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.

  • Finally write you code like this:

    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
    

Edit: 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...