Home > database >  Given an expression to be consumed by the "Where" method of an IQueryable, a nested "
Given an expression to be consumed by the "Where" method of an IQueryable, a nested "

Time:10-16

Keep in mind that the inner Any method accepts a Func<MyChildEntity, bool> argument, not a Expression<Func<MyChildEntity, bool>>.

I think I'm aware of the difference between the 2 (function pointer vs expression tree). But still, the inner Any method accepts a func, not an expression, so..

..this works:

var entities = session.Query<MyEntity>()
.Where(m => m.Children.Any(s => s.Prop == "test"))
.ToListAsync();

This doesn't:

Func<MyEntityChild, bool> childFunc = m => m.Prop == "test";

var entities = session.Query<MyEntity>()
.Where(m => m.Children.Any(childFunc))
.ToListAsync();

This doesn't work either:

var entities = session.Query<MyEntity>()
.Where(m => m.Children.Any(s => childFunc(s)))
.ToListAsync();

At the moment I'm using NHibernate to process the IQueryable, but forget about NHibernate and possible NHibernate bugs..how is the first (working) example different from the other two (not working) from the point of view of IQueryable consumer? (as stated, NHibernate in this instance..)

edit: spelling

further edit: corrected comparison from = to ==

CodePudding user response:

You cannot put Func and make query work, it should be Expression. To make your query translatable, expression should be preprocessed to make it work. It can be done by LINQKit

Activate extension:

builder
    .UseSqlServer(connectionString)
    .WithExpressionExpanding(); // enabling LINQKit extension

Then use Invoke LINQKit extension:

Expression<Func<MyEntityChild, bool>> childFunc = m => m.Prop == "test";

var entities = session.Query<MyEntity>()
    .Where(m => m.Children.Any(s => childFunc.Invoke(s)))
    .ToListAsync();

CodePudding user response:

The only problem I could find is that you're missing an = in the function:

\\ '==' instead of '='
Func<MyEntityChild, bool> childFunc = m => m.Prop == "test";

Now this should work:

var entities = session.Query<MyEntity>()
.Where(m => m.Children.Any(s => childFunc(s)))
.ToListAsync();
  • Related