To add to what AlbertK already has written but by using ExecuteSqlRaw
/ExecuteSqlRawAsync
.
The best bet is to use OUTPUT parameter
in your Stored Procedure.
Imagine a scenario where reading the StatusCode from a stored procedure
is a necessity:
CREATE PROCEDURE dbo.spIfUserExists (
@Username VARCHAR(120),
@StatusCode INT OUTPUT,
) AS
BEGIN
IF EXISTS (SELECT * FROM dbo.[Users] WHERE Username=@Username)
SET @StatusCode = 1;
ELSE
SET @StatusCode = 0;
END
You are not really returning anything but assigning an integer(INT
) to the output parameter
which will be available outside.
In your C# code, you need to create SQLParameter
object with the output parameter
name from your stored procedure
.
SqlParameter StatusCode = new SqlParameter
{
ParameterName = "@StatusCode",
SqlDbType = System.Data.SqlDbType.Int,
//Direction of this parameter is output.
Direction = System.Data.ParameterDirection.Output
};
Finally, execute ExecuteSqlRawAsync
with the required parameters for your SP.
Where @p0,@p1..@pn
indicates the positional arguments of your stored procedure.
string Username = "MyRandomUsername";
using (var ctx = new UsersDbContext())
{
await ctx.Database.ExecuteSqlRawAsync(
"spIfUserExists @p0, @StatusCode OUT",
parameters: new object[] {
Username,
StatusCode,
});
}
//StatusCode now contains the status code from the [spIfUserExists].
Console.WriteLine(Convert.ToInt32(StatusCode.Value));
The output parameters don't require the positional arguments like normal arguments do, e.g., Username
. Therefore, you don't need to pass @p[n]
to the OUTPUT arguments
but only providing them to the parameters
list.
There is no difference in coding if you're to use ExecuteSqlRaw
. You're only required to remove the await
keyword to run ExecuteSqlRaw
synchronously.
You can have more than one output parameter
in your stored procedure with different datatypes. You only need to follow the same pattern.