Strange Linq to Entities Behavior with AsExpandable()


Question

Consider the following Person entity:

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Using the following Expression (constructed using PredicateBuilder) as the criteria:

var byName = PredicateBuilder.True<Person>().And(x => x.FirstName == "Chaim");

When invoked using the following syntax, the generated SQL is fine (includes the WHERE statement):

ctx.Set<Person>().AsExpandable().Where(x => byName.Invoke(x));

However, when invoked using this slightly different syntax, no SQL WHERE is involved and the filtering is being done by Enumerable.Where instead:

ctx.Set<Person>().AsExpandable().Where(byName.Invoke);

Any thoughts?

Accepted Answer

There is no implicit conversion from a method group to an Expression (of a corresponding delegate type). There is an implicit conversion from a method group to a delegate of a matching signature. Therefore only the IEnumerable overload matches.

Of course, that's not to say that you need to use a lambda. Just write:

ctx.Set<Person>().AsExpandable().Where(ByName);

Since you're passing in an expression (ByName is, after all, an Expression<Person, bool> already, which is exactly what Queryable.Where<Person> requires) this will evaluate as a query, not in linq to objects.





Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why