Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Func<> in Entity Framework Query

I have the following Entity Framework query:

Func<Company, bool> filter;
if (officeId != 0)
    filter = company => !company.IsDeleted && company.OfficeCompanies.Any(c => c.OfficeId == officeId);
else
    filter = company => !company.IsDeleted;

var companies = from c in Repository.Query<Company>()
                where filter(c) &&
                    (relationshipTypes.Count() == 0 || relationshipTypes.Any(r => r == c.TypeEnumIndex)) &&
                    c.Description.Contains(term)
                orderby c.Description
                select new JqueryUiAutoCompleteItem
                {
                    label = c.Description,
                    value = SqlFunctions.StringConvert((double)c.Id)
                };

It gives me the error:

The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.

If I remove the reference to filter() in the main body of the query, there is no error.

I understand the meaning of this error: I am using code that cannot be converted into SQL. But what is there about my filter() that cannot be converted to SQL?

like image 543
Jonathan Wood Avatar asked Sep 13 '25 20:09

Jonathan Wood


1 Answers

You need to switch the Func to an Expression, then pass that expression to a Where directly in LINQ fluent syntax. I don't think there's a way to use the expression in query syntax.

Expression<Func<Company, bool>> filter; //<-- changed type
if (officeId != 0)
    filter = company => !company.IsDeleted && company.OfficeCompanies.Any(c => c.OfficeId == officeId);
else
    filter = company => !company.IsDeleted;

var companies = from c in Repository.Query<Company>().Where(filter) // <-- changed syntax
                where (relationshipTypes.Count() == 0 || relationshipTypes.Any(r => r == c.TypeEnumIndex)) &&
                    c.Description.Contains(term)
                orderby c.Description
                select new JqueryUiAutoCompleteItem
                {
                    label = c.Description,
                    value = SqlFunctions.StringConvert((double)c.Id)
                };
like image 65
Steve Ruble Avatar answered Sep 16 '25 10:09

Steve Ruble