scottksmith95 / LINQKit

LINQKit is a free set of extensions for LINQ to SQL and Entity Framework power users.
MIT License
1.62k stars 162 forks source link

Plugging Expressions into EntitySets / EntityCollections using compile doesnt work #173

Closed rtellez91 closed 2 years ago

rtellez91 commented 2 years ago

I'm trying to use something like this

dbContext.MainEntity.Where(me => me.ACollection.Any(Expression.Compile()).ToArrayAsync()

It compiles, but at runtime I'm getting the following:

Expression of type 'System.Func2[...,System.Boolean]' cannot be used for parameter of type 'System.Linq.Expressions.Expression1[System.Func2[...,System.Boolean]]' of method 'Boolean Any[...](System.Linq.IQueryable1[...], System.Linq.Expressions.Expression1[System.Func2[...]])' (Parameter 'arg1')

It works when used in this way:

dbContext.MainEntity.Where(me => me.ACollection.Any(ac => Expression.Invoke(ac)).ToArrayAsync()

I'm using EF Core 5 and LinqKit.Microsoft.EntityFrameworkCore 5. I'm using WithExpressionExpanding() in my DbContext registration.

I followed what this example says:

https://github.com/scottksmith95/LINQKit#plugging-expressions-into-entitysets--entitycollections-the-solution

Is the example in the page outdated?

Thanks in advance!

rtellez91 commented 2 years ago

I found how to solve it, probably it needs to be specified in the examples / documentation.

The expression that I was trying to use was returned by a function, so I was directly using in this way

ExpressionClass.Expression().Compile()

I had to declare the expression in a variable and from that variable use compile, like this var expression = ExpressionClass.Expression(); dbContext.MainEntity.Where(me => me.ACollection.Any(expression.Compile()).ToArrayAsync();

With that, the expression worked as expected with no exception returned.