IQueryable不实现IDbAsyncEnumerable

时间:2012-10-17 17:33:42

标签: entity-framework

最初在http://entityframework.codeplex.com/discussions/399499#post928179询问了这个问题。

美好的一天!请告诉我发布此问题是否错误。

我的查询如下:

IQueryable<Card> cardsQuery =
  dataContext.Cards
  .Where(predicate)
  .OrderByDescending(kc => kc.SendDate)
  .AsQueryable();

然后我尝试:

Task<Card[]> result = cardsQuery.ToArrayAsync();

然后异常上升:

The source IQueryable doesn't implement IDbAsyncEnumerable<Models.Card>

我使用'EF 5.x DbCotext generator'的修改版本。

如何避免它?

更新

重要的一点是,我有如下方法生成IQuerayble<Card>

class Repository {
  public IQueryable<Card> GetKudosCards(Func<Card, bool> predicate) {
    IEnumerable<KudosCard> kudosCards = kudosCardsQuery.Where(predicate);
     return kudosCards
            .OrderByDescending(kc => kc.SendDate)
            .AsQueryable();
  }
}

3 个答案:

答案 0 :(得分:8)

调用AsQueryable有什么意义?如果使用从IQueryable源集合(例如DbSet,ObjectSet)开始的扩展方法编写查询,则查询也将是IQueryable。

AsQueryable的目的是使用IQueryable代理/适配器包装IEnumerable集合,该代理/适配器使用能够将IQueryable查询编译为Linq to Object查询的Linq提供程序。当您想要使用内存数据查询时,这可能很有用。

为什么需要AsQueryable调用?如果您只是删除它会怎么样?

<强>更新

哦,好吧,现在看来我理解你的问题了。快速查看ODataQueryOptions.ApplyTo后,我意识到它只是扩展了查询的基础表达式树。您仍然可以使用它以您想要的方式运行查询,但是您需要一个小技巧来将查询转换回通用。

IQueryable<Card> cardsQuery =
   dataContext.Cards
    .Where(predicate)
    .OrderByDescending(kc => kc.SendDate);


IQueryable odataQuery = queryOptions.ApplyTo(cardsQuery);

// The OData query option applier creates a non generic query, transform it back to generic
cardsQuery = cardsQuery.Provider.CreateQuery<Card>(odataQuery.Expression);

Task<Card[]> result = cardsQuery.ToArrayAsync();

答案 1 :(得分:3)

问题如下。

我有一个方法:

class Repository {
  public IQueryable<Card> GetKudosCards(Func<Card, bool> predicate) {
    IEnumerable<KudosCard> kudosCards = kudosCardsQuery.Where(predicate);
    return kudosCards
            .OrderByDescending(kc => kc.SendDate)
            .AsQueryable();
  }
}

问题是kudosCards的类型为IEnumerable<KudosCard>。抛出异常。如果我将谓词类型更改为Expression<Func<Card, bool> predicate,那么一切正常。

答案 2 :(得分:0)

我在使用 LinqKit 库表达式构建器时遇到了同样的问题,最终生成了 AsQueryable()
非常令人惊讶的是,它发生在我的 XUnit 集成测试调用中。

我很想知道为什么在通过 Swagger 调用相同的 API 端点时没有发生同样的问题。


结果我不得不做一个基本的改变。
我不得不更换:

using System.Data.Entity;

与:

using Microsoft.EntityFrameworkCore;

在我调用 LinqKit 表达式方法的地方。

相关问题