简体   繁体   中英

Using Expression Class With LINQ Queries

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

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM