3

I have a stored procedure which inserts new records from service to the database or update existing record. But I need to display true if it is inserted/updated successfully and if it fails, I need to display false in response.

so in my stored procedure call from EF

result = database.usp_sp_name(parameters);
if (result==0)
    return true;
else 
    return false;

I tried the above code since I read in MSDN site that if successful transaction means, result will be 0. But even its inserting record or updating record, I am getting response as false.

Almir Vuk
  • 2,983
  • 1
  • 18
  • 22
Raj
  • 343
  • 3
  • 13
  • That should work. If you call that SP from Management Studio, it returns 0? You can debug the code for the SP in Entity Framework, there you can see how it's called and what it returns. If it's not working, you should at least be able to find what's the exact point that is failing. – Andrew Jul 29 '16 at 19:45
  • Does the stored proc return a value at the end of the proc? – grambo25 Jul 29 '16 at 20:32
  • Nope. I meant return_Value parameter which is default in stored procedure – Raj Jul 29 '16 at 20:33
  • Did you tried that? http://stackoverflow.com/questions/14130661/why-is-entity-framework-calling-my-stored-procedure-but-returning-an-incorrect-v http://stackoverflow.com/questions/14735477/get-return-value-from-stored-procedure http://stackoverflow.com/questions/22440896/stored-procedure-always-returning-0 http://stackoverflow.com/questions/24253522/stored-procedure-returns-incorrect-scalar-value-of-1-instead-of-return-value#autocomment64725743 – Manish Kumar Jul 30 '16 at 10:20
  • You should include the code that executes the sproc. It's not clear how this relates to Entity Framework. – Gert Arnold Jul 31 '16 at 10:13

1 Answers1

1

In your code, create a bool that will hold the result of your storedproc and will return true if the result of your storedproc is 1. Otherwise false.

bool result = _entites.StoredProc(parameters);
return (result == 1) ? true: false;

But in your stored proc You should create a procedure that will return a value like this

CREATE PROCEDURE [dbo].[StoredProc]
    @parameter
AS
BEGIN
    DECLARE @result int
    DECLARE @param nvarchar(255)
    SET @param = @parameter

    INSERT INTO (field1) VALUES (@param)

    IF @@ERROR = 0
        SET @result = 1
    ELSE 
        SET @result = 0

RETURN @result

@@Error returns 0 if the T-SQl statement encountered no errors. You can use that to set the result to 1 or 0. Refer to this link for more info for @@error.

Raymond Dumalaog
  • 353
  • 4
  • 13