sql-serverasp.net-core-mvcef-core-8.0

Stored procedure with multiple parameters in EF Core 8


I am trying to use a stored procedure with multiple parameters but I keep getting a 500 response from my API. The stored procedure returns a string result and takes 3 varchar(30) parameters.

Stored procedure call:

string Item1 = "123";
DateTime Item2 = DateTime.Now.AddDays(-3);
DateTime Item3 = DateTime.Now;

var result = await context.Set<string>().FromSqlInterpolated
            ($"EXECUTE proc @item1={Item1}, @item2={Item2.ToString()}, @item3={Item3.ToString()}")
            .FirstOrDefaultAsync();

Any help would be greatly appreciated, thank you!


Solution

  • For scalar results, you don't use the Set<> function as it's not an entity set. Just use context.Database.SqlQuery<>

    var result = await context.Database.SqlQuery<string>()
                ($"EXECUTE proc @item1={Item1}, @item2={Item2.ToString()}, @item3={Item3.ToString()}")
                .FirstOrDefaultAsync();
    

    Note that you should only do ToString if the parameter is a string, otherwise pass the value as the correct data type directly.