I\'ve bunch of SPs that are used for invocation from my c# console application. So, I\'m using EF \"data base first\" approach, which is rather convinient for me, because EF ge
Your DbContext represents the model of a database. It hides for you how the database actually is called.
Stored procedures are part of your database. Your DbContext should provide a function to call the stored procedure, while hiding that a stored procedure is used to perform the function. In other words: users of your DbContext don't care whether the function is performed using a query or SQL execute, or using a stored procedure. It could be a SQL statement and later be changed into a stored procedure without users having to know that it is changed.
Calling a stored procedure is done using DbContext.DataBase.ExecuteSqlCommand. There is an async awaitable function DbContext.DataBase.ExecuteSqlCommandAsync
class MyDbContext : DbContext
{
... // DbSets
public async Task DoSomethingAsync(...)
{
object[] params = new Object[]
{
new SqlParameter(@"ParamX", ...),
new SqlParameter(@"ParamY", ...);
}
const string SqlCommand = @"Exec MyStoredProcedure
@ParamX,
@ParamY);
return await this.Database.ExecuteSqlCommandAsync(sqlCommand, params);
}
Similarly, if you don't want to call a Stored Procedure but a LINQ query on DbSets you can use the async extension functions of DbSet
var result = await dbContext.MyItems
.Where(item => ...)
.GroupBy(item => ...)
.OrderBy(group => ...)
.FirstOrDefaultAsync();
Note, that as that use deferred execution only will change the Expression of the IQueryable. It is the function without deferred execution (ToList, Any, First, Max, ...) that will cause the Provider to execute the Expressions. So only those function need an async version