Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting stored procedure output parameter with LINQ and Entity Framework

I've created a stored procedure that takes parameters to create a user. If the user already exists it sets the output parameter to 'User already exists' and does nothing more.

Now I've mapped this function (InsertNewUser) to my Entity Framework and am calling it like so:

context.InsertNewUser(email, name, passwordhash, salt, ???)

The ??? is where I'm having trouble. In the stored procedure this parameter is an OUTPUT parameter. I tried declaring a string and then passing in "out declaredString" but that wasn't correct.

I'm not sure I'm going about this the right way, any thoughts?

This is the Stored Procedure:

ALTER PROCEDURE dbo.InsertNewUser

    (
    @eMail nvarchar(256),
    @firstName nvarchar(256),
    @lastName nvarchar(256),
    @passwordHash nvarchar(256),
    @salt nvarchar(256),
    @output nvarchar(256) OUTPUT
    )

AS
    /* Saves a user to the db. */
    BEGIN
    --First check if the user doesn't exist
    IF EXISTS (SELECT eMail FROM UserSet WHERE eMail = @eMail)  
        --Return that user exists
        SET @output = 'User exists' 
    ELSE    
        INSERT INTO UserSet
        VALUES (@eMail, @firstName, @lastName, @passwordHash, @salt)
    END
like image 585
Phil Avatar asked Oct 16 '10 19:10

Phil


People also ask

Can stored procedure have output parameter?

A Stored Procedure can have any number of output parameters. The simple logic is this — If you want to return 1 value then use 1 output parameter, for returning 5 values use 5 output parameters, for 10 use 10, and so on.

Can we use LINQ with stored procedure?

In LINQ to SQL, we can use stored procedures with or without parameters to get the required data from database tables. Before we start using LINQ to SQL with a stored procedure, we need to create a database with required tables and map those tables to LINQ to SQL file (. dbml).

Can we use Entity Framework with stored procedure?

The Entity Framework has the capability of importing a Stored Procedure as a function. We can also map the result of the function back to any entity type or complex type.


1 Answers

You can also write in the following way:

string output = "";    
context.InsertNewUser(email, name, passwordhash, salt, ref output)
like image 151
Fore Avatar answered Sep 27 '22 22:09

Fore