dotnet / dotnet/efcore

Support Async IEnumerable to IQueryable mapping extension (As(Async)Queryable)

Open
#32,893 18 comments 5 reactions 0 assignees View on GitHub
area-query customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

I encountered this issue while unit testing, to "mock" away a IQueryable with hardcoded values. While investigating I found following things:

1. AsQueryable returns a System.Linq.EnumerableQuery (Runtime Library) instance that does not implement IAsyncQueryProvider
2. IAsyncQueryProvider is part of ef core so System.Linq.EnumerableQuery can't implement it
3. Ef Core could provide a AsAsyncQueryable extension method that returns a custom Microsoft.EntityFrameworkCore.Query.AsyncEnumerableQuery implementation
4. AsyncEnumerableQuery implements IAsyncQueryProvider and provides an implementation that simply maps async calls to sync calls

This would allow usage patterns like the following:
```csharp
[Fact]
public async Task TestCountAsync() {
var queryable = new[] {
new WeatherForecastEntity {
Id = new Guid("0224589c-bc34-4761-b8e6-8b95aba85a00"),
Date = new DateOnly(2010, 01, 01),
TemperatureC = 12,
CreatedAt = new DateTimeOffset(2023, 10, 23, 0, 0, 0, TimeSpan.Zero)
}
}.AsAsyncQueryable();
(await queryable.CountAsync()).Should().Be(1);
}
```

There is definitely a need when looking at following libraries:
https://www.nuget.org/packages/MockQueryable.EntityFrameworkCore
https://github.com/romantitov/MockQueryable
https://github.com/scott-xu/EntityFramework.Testing

The current Version of MockQueryable.EntityFrameworkCore has > 2.000.000 downloads.

Moving the code into ef core would ensure that it always stays up-to-date with the current ef implementation. Additionally (especially) for new users the fact that 'IQueryable' doesn't implement 'IAsyncQueryProvider' and throws an exception is kind of unexpected when using AsQueryable, because most new code is async nowadays.

I quickly sketched something that wraps the System.Linq.EnumerableQuery implementation with additional async support:
https://github.com/swimmesberger/AsyncEnumerableQuery

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.