Reputation: 500
I was wondering if there's a way to use Expression class for custom queries with LINQ queries such as this
Expression<Func<TEntity, bool>> expression = (x) => x.Id = 1
var items = from item in context.TEntity
where expression
select item
I know there's a way to do this using LINQ function as the Where function takes an expression as a parameter but I really need to do this using LINQ queries
note: the code above is just an example to make you get around what I'm trying to do it's not an actual working code
note 2: I need this to work with Entity Framework
Upvotes: 3
Views: 327
Reputation: 33833
Unfortunately, Entity Framework does not natively support this type of expression projection, which is why a common attempt such as where expression.Compile().Invoke(item);
will throw an exception at runtime.
However, if you use the LinqKit library (which utilizes the Expression Visitor) and call .AsExpandable()
on the entity set, you can then invoke your expression dynamically:
Expression<Func<TEntity, bool>> expression = x => x.Id == 1;
var items = from item in context.Set<TEntity>.AsExpandable()
where expression.Invoke(item)
select item;
Upvotes: 4
Reputation: 28272
This works, at least on EF Core (I have just tested it). Don't have any EF6 project handy where I could test.
Expression<Func<TEntity, bool>> expression = (x) => x.Id = 1
var items = from item in context.TEntity
where expression.Compile()(item);
select item
Update: I just made a simple test project on EF6 and it does not work there, since it doesn't recognize the expression invocation
Upvotes: 1