0

I can do the following in Entity Framework Core 2.0:

Expression<Func<MyFirstEntity, bool>> myExpression = entity => entity.SomeProperty == true;
List<MyFirstEntity> myItems = context.MyFirstEntity.Where(myExpression).ToList();

MyFirstEntity has a foreign key to MySecondEntity. So I can use a navigation property in MySecondEntity.

Example:

List<MySecondEntity> myItems = context.MySecondEntity
    .Where(secondEntity  => secondEntity.MyFirstEntities
         .Any(firstEntity => firstEntity.SomeProperty == true)).ToList();

I would like to use myExpression in the query. Something like this would be nice:

List<MySecondEntity> myItems = context.MySecondEntity
    .Where(secondEntity  => secondEntity.MyFirstEntities
         .Any(myExpression)).ToList(); 

But this gives a compile time error, because secondEntity.MyFirstEntities does not implement IQueryable. Defining a Func<MyFirstEntity, bool> for using in navigation properties does also not work (runtime error, because Entity Framework does not know the defined Func).

My current solution would be something like this:

List<MySecondEntity> myItems = context.MySecondEntity
    .Where(secondEntity  => context.MyFirstEntities
         .Where(firstEntity => firstEntity.SecondEntityId == secondEntity.Id)
         .Any(myExpression)).ToList();

This does somewhat undermine the purpose of navigation properties.

Is there a better solution?

Why are navigation properties not ´IQueryable`? They have to be transformed into SQL somehow. How does the Entity Framework do this, without expressions?

Also I noticed the resulting queries in my two working examples are different, but I so far did not notice any performance differences. Are there any?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Fabian S.
  • 909
  • 6
  • 20

1 Answers1

0

So I found the solution. LINQKit to the rescue. Working example with AsExpndable() and Compile():

List<MySecondEntity> myItems = context.MySecondEntity.AsExpandable()
    .Where(secondEntity  => secondEntity.MyFirstEntities
        .Any(myExpression.Compile())).ToList(); 
Fabian S.
  • 909
  • 6
  • 20