【问题标题】:What can I use instead of Where clause in Asyn method?我可以使用什么来代替异步方法中的 Where 子句?
【发布时间】:2016-02-02 22:02:10
【问题描述】:

我有一个 C# 和实体框架项目。我需要将 Repository 的一些方法转换为 Async。我在转换此方法时遇到问题,不确定我可以使用什么来代替 Where 子句。

    public async Task<IEnumerable<Product>> GetProductByYearIdAsync(int yearId)
    {
        return await ApplicationsContext.Product.Where(product=> product.YearId == yearId);
    }

当我使用它时,它给了我无法等待 iQueryable 的错误。当我使用 FirstOrDefaultAsync 时,我知道如何转换为 IEnumerable。

【问题讨论】:

    标签: c# entity-framework asynchronous


    【解决方案1】:

    你最后错过了.ToListAsync()。那是实际的异步操作,而不是.Where(

    请注意,您必须确保程序集引用了 EntityFramework dll,并且您在 using 语句中包含命名空间 System.Data.Entity,因为这是 a extension method

    【讨论】:

      【解决方案2】:

      Where 并不实际执行查询,因此调用Where 并没有什么“异步”。您需要调用ToListAsync,它实际上是异步执行查询。

      public async Task<IEnumerable<Product>> GetProductByYearIdAsync(int yearId)
      {
          return await ApplicationsContext.Product
              .Where(product=> product.YearId == yearId).ToListAsync();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多