Share via

Executing Complex Stored Procedure with Entity Framework

Kmcnet 1,356 Reputation points
2026-02-13T18:28:34.4766667+00:00

Hello everyone and thanks for the help in advance. I want to execute a complex stored procedure using Entity Framework. The sproc accepts two parameters and returns either 0 or 1 depending on whether it was successful. I tried:

var res = ctx.myTable.FromSqlRaw("Exec sproc @Param1, @Param2", new SqlParameter("@Param1", @Param1), new SqlParameter("@Param1" @Param1));

But the update fails to work. Do I just need to go with ADO? Any help would be appreciated.

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments
{count} votes

Answer accepted by question author
  1. Q&A Assist
    2026-02-13T18:28:44.0066667+00:00
    AI generated content. This question contains an answer created with AI from Q&A Assist. Learn more

    To execute a complex stored procedure with Entity Framework that accepts parameters, you should ensure that you are correctly passing the parameters and using the right method for execution. In your example, there is a small mistake in the parameter definition. You are using @Param1 twice instead of using @Param2 for the second parameter. Here's how you can correct it:

    var res = ctx.myTable.FromSqlRaw("EXEC sproc @Param1, @Param2",  
        new SqlParameter("@Param1", param1Value),  
        new SqlParameter("@Param2", param2Value));
    

    Make sure to replace param1Value and param2Value with the actual values you want to pass to the stored procedure. This should work as long as the stored procedure is set up correctly and the parameters are valid.

    If you still encounter issues, you might want to check the following:

    • Ensure that the stored procedure is correctly defined in the database.
    • Verify that the parameters being passed match the expected types in the stored procedure.
    • Check for any exceptions or errors that might provide more insight into why the execution is failing.

    If the problem persists and you need more control or flexibility, using ADO.NET directly is also a valid approach.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. AgaveJoe 31,176 Reputation points
    2026-02-13T19:28:52.88+00:00

    Hi @Kmcnet,

    There are a few reasons why your current approach isn't working. The primary issue is a mismatch between what your Stored Procedure returns and how FromSqlRaw is designed to function. Also, I think it is important to mention that Entity Framework takes advantage of ADO.NET under the hood.

    Return Type Mismatch

    You mentioned the procedure returns a 0 or 1, but you are calling it from ctx.myTable. In Entity Framework, FromSqlRaw on a DbSet expects the SQL command to return a result set (table) that matches the schema of that specific entity (myTable).

    If the procedure only returns a scalar value (like a RETURN statement or a single SELECT), EF cannot map that to your table object, and it will likely fail or return null.

    Execution vs. Querying

    If your Stored Procedure performs an Update and returns a status, you should not be using FromSqlRaw. Instead, use ExecuteSqlRawAsync (or the synchronous version). This is designed for commands that modify data and return the number of rows affected.

    Corrected Pattern:

    var param1 = new SqlParameter("@Param1", value1);
    var param2 = new SqlParameter("@Param2", value2);
    
    // Use ExecuteSqlRaw for Updates/Commands
    // This returns the number of rows affected by the SP
    int rowsAffected = await ctx.Database.ExecuteSqlRawAsync("EXEC sproc @Param1, @Param2", param1, param2);
    
    if (rowsAffected > 0) {
        // Success logic
    }
    
    

    Syntax Errors in your Snippet

    There are also two technical errors in your current code that will prevent compilation:

    Duplicate Parameters: You defined @Param1 twice in your SqlParameter list. The second one should likely be @Param2.

    Missing Comma: There is a missing comma between the string and the variable in your second SqlParameter constructor.

    How are you returning the 0/1?

    If you specifically need to capture a RETURN value from the SQL (e.g., RETURN 1), you must define a parameter with Direction = ParameterDirection.Output or ReturnValue.

    Code Example for a Return Value:

    using Microsoft.Data.SqlClient;
    using System.Data;
    
    // 1. Define the parameters (fixing the duplicate @Param1 error)
    var p1 = new SqlParameter("@Param1", value1);
    var p2 = new SqlParameter("@Param2", value2);
    
    // 2. Define a parameter specifically for the RETURN value
    var returnCode = new SqlParameter {
        ParameterName = "@ReturnCode",
        SqlDbType = SqlDbType.Int,
        Direction = ParameterDirection.ReturnValue
    };
    
    // 3. Execute the command (Note: the returnCode must be included in the SQL string)
    await ctx.Database.ExecuteSqlRawAsync("EXEC @ReturnCode = sproc @Param1, @Param2", returnCode, p1, p2);
    
    // 4. Access the value
    int result = (int)returnCode.Value; 
    bool isSuccess = result == 1;
    
    
    

    Code Example for Output Variable:

    using Microsoft.Data.SqlClient;
    using System.Data;
    
    // 1. Define input parameters
    var p1 = new SqlParameter("@Param1", value1);
    var p2 = new SqlParameter("@Param2", value2);
    
    // 2. Define the OUTPUT parameter
    var isSuccessParam = new SqlParameter {
        ParameterName = "@IsSuccess",
        SqlDbType = SqlDbType.Bit, // or SqlDbType.Int
        Direction = ParameterDirection.Output
    };
    
    // 3. Execute the command
    // Note: You must include 'OUTPUT' in the SQL string for it to map correctly
    await ctx.Database.ExecuteSqlRawAsync("EXEC sproc @Param1, @Param2, @IsSuccess OUTPUT", p1, p2, isSuccessParam);
    
    // 4. Retrieve the value after execution
    bool isSuccess = (bool)isSuccessParam.Value;
    
    if (isSuccess) {
        // Proceed with success logic
    }
    
    

    You can also return a scalar type depending on the version of EF you are using.

    https://learn.microsoft.com/en-us/ef/core/querying/sql-queries?tabs=sqlserver#querying-scalar-non-entity-types

    https://learn.microsoft.com/en-us/ef/core/querying/sql-queries?tabs=sqlserver


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.