从ASPNetBoilerplate中的SqlQuery的自定义存储库访问ToListAsync()

时间:2017-08-03 18:02:55

标签: c# entity-framework asynchronous repository-pattern aspnetboilerplate

我正在使用ASP.Net Boilerplate。我已经实现了IRepository来创建自定义存储库,因此我可以添加一个自定义方法来从存储过程返回数据。但是,无论我如何构建Task,异步或等待组件,我都会收到以下错误:

System.InvalidOperationException: The provider for the source IQueryable doesn't implement IDbAsyncQueryProvider. Only providers that implement IDbAsyncQueryProvider can be used for Entity Framework asynchronous operations. For more details see http://go.microsoft.com/fwlink/?LinkId=287068.

我的存储库看起来像:

namespace myApp.EntityFramework.Repositories
{
    public class TruckRepository : UHaulTrucks.HoustonRepositoryBase<DailyDockQuery>, ITruckRepository
    {

        public TruckRepository(IDbContextProvider<UHaulHoustonDbContext> dbContextProvider) : base(dbContextProvider)
        {

        }

  public IQueryable<DailyDockQuery> GetDailyDockQuery()
        {

           var ret = Context.Database.SqlQuery<DailyDockQuery>("exec Central_DailyDockQuery").AsQueryable();
            return ret;
        }
   }
}

我的服务:

public async Task<PagedResultOutput<DailyDockQueryListDto>> GetDailyDockQuery()
        {
            var query = _truckRepository.GetDailyDockQuery();

            var dailyCount = await query.CountAsync();


            var dailies = await query.ToListAsync();

            var dailiesDtos = dailies.MapTo<List<DailyDockQueryListDto>>();

            return new PagedResultOutput<DailyDockQueryListDto>(
                dailyCount,
                dailiesDtos
                );
        }

上述错误将在任何尝试执行异步方法时生成,例如:

var dailyCount = await query.CountAsync();

var dailies = await query.ToListAsync();

正如我所提到的,我已经尝试使用任务和异步组合在存储库和服务中使用相同结果的几种变体。我是以这种方式实现自定义存储库的新手,并怀疑我应该从IRepository获得CountAsync和ToListAsync的好处,我仍然需要在自定义类中实现它们。

非常感谢任何帮助。仍然在这里找到我的路。

1 个答案:

答案 0 :(得分:0)

在Aspnetboilerplate中执行存储过程(选择记录)示例代码:

public async Task<List<string>> GetUserNames()
{
    EnsureConnectionOpen();

    using (var command = CreateCommand("GetUsernames", CommandType.storedProcedure))
    {
        using (var dataReader = await command.ExecuteReaderAsync())
        {
            var result = new List<string>();

            while (dataReader.Read())
            {
                result.Add(dataReader["UserName"].ToString());
            }

            return result;
        }
    }
}

我强烈建议您阅读有关在Aspnetboilerplate中使用存储过程的文档。您需要的一切:https://aspnetboilerplate.com/Pages/Documents/Articles/Using-Stored-Procedures,-User-Defined-Functions-and-Views/index.html