AutoMapper unable to cast TestDbAsyncEnumerable to IQueryable

I ran into this same problem, in addition to the accepted answer you might also have the generic version of CreateQuery like I do - I fixed that too like this:

public IQueryable<TElement> CreateQuery<TElement>(Expression expression)
{
    var queryType = typeof(TestDbAsyncEnumerable<>).MakeGenericType(typeof(TElement));
    return (IQueryable<TElement>)Activator.CreateInstance(queryType, expression);
}

The type is being provided by TElement, so its a simplier implementation on the generic version.


Edit your TestDbAsyncQueryProvider<>.CreateQuery() so that it returns the right type of the expression passed by ProjectTo<>.

Here is my sample implementation.

public IQueryable CreateQuery(Expression expression)
{
    switch (expression)
    {
        case MethodCallExpression m:
            {
                var resultType = m.Method.ReturnType; // it shoud be IQueryable<T>
                var tElement = resultType.GetGenericArguments()[0];
                var queryType = typeof(TestDbAsyncEnumerable<>).MakeGenericType(tElement);
                return (IQueryable)Activator.CreateInstance(queryType, expression);
            }
    }
    return new TestDbAsyncEnumerable<TEntity>(expression);
}

https://gist.github.com/masaedw/95ab972f8181de6bbe48a20ffe9be113

I have written also unit test. It's working.

https://github.com/masaedw/AutoMapper/blob/TestDbAsync/src/IntegrationTests/MockedContextTests.cs