Unable to refactor using LINQ to Entities and LinqKit / PredicateBuilder

entity-framework-4 expression-trees linqkit linq-to-entities predicatebuilder

Question

I have been trying to refactor a LINQ expression into a method, and have been running into both the "Internal .NET Framework Data Provider error 1025." and "The parameter 'xyz' was not bound in the specified LINQ to Entities query expression." exceptions.

Here are the relevant parts of the entity model (using EF 4.2 / LINQ to Entities):

public class Place : Entity
{
    public string OfficialName { get; protected internal set; }
    public virtual ICollection<PlaceName> { get; protected internal set; }
}

public class PlaceName : Entity
{
    public string Text { get; protected internal set; }
    public string AsciiEquivalent { get; protected internal set; }
    public virtual Language TranslationTo { get; protected internal set; }
}

public class Language : Entity
{
    public string TwoLetterIsoCode { get; protected internal set; }
}

The basic relational model is this:

Place (1) <-----> (0..*) PlaceName (0..*) <-----> (0..1) Language

I am trying to create a query which will, when given a search term, try to find Place entities whose OfficialName starts with the term OR who has a PlaceName whose Text or AsciiEquivalent starts with the search term. (Language isn't where I'm having trouble, though it is part of the query, because PlaceNames should only match for the CultureInfo.CurrentUICulture.TwoLetterIsoLanguageName.)

The following code does work:

internal static IQueryable<Place> WithName(this IQueryable<Place> queryable, 
    string term)
{
    var matchesName = OfficialNameMatches(term)
        .Or(NonOfficialNameMatches(term));
    return queryable.AsExpandable().Where(matchesName);
}

private static Expression<Func<Place, bool>> OfficialNameMatches(string term)
{
    return place => place.OfficialName.StartsWith(term);
}

private static Expression<Func<Place, bool>> NonOfficialNameMatches(string term)
{
    var currentLanguage = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
    return place => place.Names.Any(
        name =>
        name.TranslationToLanguage != null
        &&
        name.TranslationToLanguage.TwoLetterIsoCode == currentLanguage
        &&
        (
            name.Text.StartsWith(term)
            ||
            (
                name.AsciiEquivalent != null
                &&
                name.AsciiEquivalent.StartsWith(term)
            )
        )
    );
}

What I am trying to do next is refactor the NonOfficialNameMatches method to extract the name => ... expression out into a separate method, so that it can be reused by other queries. Here is one example I have tried, which does not work and throws the exception "The parameter 'place' was not bound in the specified LINQ to Entities query expression.":

private static Expression<Func<Place, bool>> NonOfficialNameMatches(string term)
{
    return place => place.Names.AsQueryable().AsExpandable()
        .Any(PlaceNameMatches(term));
}

public static Expression<Func<PlaceName, bool>> PlaceNameMatches(string term)
{
    var currentLanguage = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
    return name =>
            name.TranslationToLanguage != null
            &&
            name.TranslationToLanguage.TwoLetterIsoCode == currentLanguage
            &&
            (
                name.Text.StartsWith(term)
                ||
                (
                    name.AsciiEquivalent != null
                    &&
                    name.AsciiEquivalent.StartsWith(term)
                )
            );
}

When I don't have the .AsExpandable() chain in NonOfficialNameMatches, then I get the "Internal .NET Framework Data Provider error 1025." exception.

I have followed other advice here such as several combinations of invoking .Expand() on the predicates, but always end up with one of the aforementioned exceptions.

Is it even possible to factor out this expression into a separate method using LINQ to Entities with LinqKit / PredicateBuilder? If so, how? What am I doing wrong?

Accepted Answer

The method below should work:

private static Expression<Func<Place, bool>> NonOfficialNameMatches(string term)
{
    Expression<Func<PlaceName, bool>> placeNameExpr = PlaceNameMatches(term);
    Expression<Func<Place, bool>> placeExpr =
        place => place.Names.Any(name => placeNameExpr.Invoke(name));
    return placeExpr.Expand();
}

EDIT: Adding additional explanations

The PlaceNameMatches method works as you wrote it. Your issues were in how you used the method. If you want to factor out parts of an expression follow the 3 steps I did in the method above.

  1. Set a local variable to the expression created by a method.

  2. Set another local variable to a new expression that Invokes the local variable expression.

  3. Call the LinkKit Expand method: this will expand any Invoked expressions



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