Howto use predicates in LINQ to Entities for Entity Framework objects

Posted by user274947 on Stack Overflow See other posts from Stack Overflow or by user274947
Published on 2013-10-27T09:49:13Z Indexed on 2013/10/27 9:53 UTC
Read the original article Hit count: 233

I'm using LINQ to Entities for Entity Framework objects in my Data Access Layer.

My goal is to filter as much as I can from the database, without applying filtering logic on in-memory results.

For that purpose Business Logic Layer passes a predicate to Data Access Layer.

I mean

Func<MyEntity, bool>

So, if I use this predicate directly, like

public IQueryable<MyEntity> GetAllMatchedEntities(Func<MyEntity, Boolean> isMatched)
{
    return qry = _Context.MyEntities.Where(x => isMatched(x));
}

I'm getting the exception

[System.NotSupportedException] --- {"The LINQ expression node type 'Invoke' is not supported in LINQ to Entities."}

Solution in that question suggests to use AsExpandable() method from LINQKit library.

But again, using

public IQueryable<MyEntity> GetAllMatchedEntities(Func<MyEntity, Boolean> isMatched)
{
    return qry = _Context.MyEntities.AsExpandable().Where(x => isMatched(x));
}

I'm getting the exception

Unable to cast object of type 'System.Linq.Expressions.FieldExpression' to type 'System.Linq.Expressions.LambdaExpression'

Is there way to use predicate in LINQ to Entities query for Entity Framework objects, so that it is correctly transformed it into a SQL statement.

Thank you.

© Stack Overflow or respective owner

Related posts about c#

Related posts about entity-framework