efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Filter subquery on Include()

Open BenjiZombie opened this issue 11 years ago • 5 comments

I could not find any references to this question, please close if dupe.

I'm trying to filter elements of a subquery using LINQ but I keep getting the following error:

InvalidCastException: Unable to cast object of type
'Remotion.Linq.Clauses.Expressions.SubQueryExpression' to type     
'System.Linq.Expressions.MemberExpression'.

Here's my code (I want to load the only Page model and it's current culture translation; I want to avoid having to load all the translations from the DB, obviously.)

var page = _dbContext
    .Pages
    .Include(p => p.Translations.SingleOrDefault(e => e.CultureName == CultureInfo.CurrentCulture.Name))
    .SingleOrDefault();

Is this something that is supported, or am I doing the wrong query?

Thanks

BenjiZombie avatar Oct 19 '15 19:10 BenjiZombie

It is not supported. Accesses to navigation properties are the only kind of expressions allowed inside Include() and ThenInclude(). The following query using a projection should be equivalent to what you want though:

var page = _dbContext
    .Pages
    .Select(p => new 
    {
        Page = p, 
        Translations = p.Translations.SingleOrDefault(
            e => e.CultureName == CultureInfo.CurrentCulture.Name)
    })
    .SingleOrDefault()
    .Page;

Note that I just wrote this by hand and didn't try to compile it or run it. I very likely made mistakes and it is still possible that you may hit other EF7 limitations.

Could you please try that and report back if it works for you?

divega avatar Oct 19 '15 20:10 divega

@divega Thanks for your support.

Unfortunately, it produces another error. I also noticed 2 runtime warnings while executing the code:

Microsoft.Data.Entity.Query.QueryCompilationContext: Warning: The LINQ expression '(Property([p], "PageId") == Property([e], "Id"))' could not be translated and will be evaluated locally.
Microsoft.Data.Entity.Query.QueryCompilationContext: Warning: The LINQ expression 'SingleOrDefault()' could not be translated and will be evaluated locally.

And here's the resulting exception:

Exception thrown: 'System.InvalidOperationException' in EntityFramework.Core.dll
Microsoft.AspNet.Diagnostics.DeveloperExceptionPageMiddleware: Error: An unhandled exception has occurred while executing the request
System.InvalidOperationException: The EF.Property<T> method may only be used within LINQ queries.
   at Microsoft.Data.Entity.EF.Property[TProperty](Object entity, String propertyName)
   at lambda_method(Closure , QueryResultScope )
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
   at lambda_method(Closure , QueryResultScope )
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
   at lambda_method(Closure )
   at Microsoft.Data.Entity.Query.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
   at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
   at Microsoft.Data.Entity.Query.QueryCompiler.<>c__DisplayClass16_1`1.<CompileQuery>b__1(QueryContext qc)
   at Microsoft.Data.Entity.Query.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.Data.Entity.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source)

Anyhow, I'll try to think of something else since it's not supported.

BenjiZombie avatar Oct 20 '15 12:10 BenjiZombie

Thanks for trying. This is good data. The exception has been reported before and it is a bug. We now know we can use this query pattern to reproduce it. (Cc @maumar)

In the meanwhile, the other thing you can try is to issue two queries:

var page = _dbContext.Pages.SingleOrDefault();
var translations = _dbContext.Translations.SingleOrDefault(
   e => e.CultureName == CultureInfo.CurrentCulture.Name && e.Page.Id == page.Id);

At the end of this the relationships between the objects shoukd be fixed up the page.Translation collection should contain the one translation retrieved by the query.

divega avatar Oct 20 '15 12:10 divega

This is the direction I am currently going for. Thanks again.

BenjiZombie avatar Oct 20 '15 14:10 BenjiZombie

The Property exception is being tracked by https://github.com/aspnet/EntityFramework/issues/3452 so closing this one out.

rowanmiller avatar Oct 22 '15 18:10 rowanmiller