How to generate stored procedures as async methods through EF in c# application?

后端 未结 1 653
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-27 08:41

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

1条回答
  •  旧时难觅i
    2021-01-27 09:25

    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

    0 讨论(0)
提交回复
热议问题