I am using ASP.NET Core Entity Framework and I would like to call a simple stored procedure.
I created the stored procedure in my migrations like this:
public partial class spGetAvailableCourses : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
var sp = @"CREATE PROCEDURE [dbo].[GetAvailableCourses]
AS
BEGIN
SELECT COUNT(courses.Enrolled) FROM Courses WHERE Courses.Capacity > Courses.Enrolled;
END";
migrationBuilder.Sql(sp);
}
I can call the stored procedure in SQL Server with the following command.
EXEC dbo.GetAvailableCourses
But when I try and call the stored procedure in in my ICourseRepository, it doesn't work, I get minus one returned.
Can someone please tell me the correct of calling the stored procedure? Thanks
public class CourseRepository : ICourseRepository
{
private readonly DataContext _context;
public CourseRepository(DataContext context)
{
_context = context;
}
public Task<CoursesAvailableCount> CoursesAvailableCount()
{
var ss = _context.Database.ExecuteSqlRaw("GetAvailableCourses");
return null;
}
I also tried
public async Task<CoursesAvailableCount> CoursesAvailableCount()
{
var s = await _context.Database.ExecuteSqlCommandAsync("GetAvailableCourses");
}
ExecuteSqlRawreturns the number of affected rows. It is the wrong method to call for a count result.GetAvailableCoursestoGetAvailableCourseCountas I would expect a list of courses fromGetAvailableCoursesif I knew nothing else about that SP other than the name.