Question

I am trying to load in navigation properties using the IQueryable Include method, however although the expression is correct I am not getting any results

here is the code

protected void LoadNavigationProperty(ref IQueryable<T> query, Expression<Func<T, object>>[] navigationProperties)
{
    if ((query != null) && (navigationProperties != null))
    {
        foreach (Expression<Func<T, object>> navigationProperty in navigationProperties)
        {
            query.Include<T, object>(navigationProperty);
        }
    }
}

I put a break point on query.Include and checked the data:

navigationProperties[0] = { n => n.UserStatus }  
navigationProperties[1] = { n => n.PrivilegeLevel }

after stepping past the include line I checked the queries value again and found that it did not include the nav properties

Was it helpful?

Solution

Include() does not change query instance, it returns new one. You need to assign it back to query:

protected void LoadNavigationProperty(ref IQueryable<T> query, Expression<Func<T, object>>[] navigationProperties)
{
    if ((query != null) && (navigationProperties != null))
    {
        foreach (var navigationProperty in navigationProperties)
        {
            query = query.Include<T, object>(navigationProperty);
        }
    }
}

OTHER TIPS

Marcin explains why it did not work (.Include( does modify the query) however I just wanted to give you an alternate way of doing it so you can use the method as an extension method so it could be used in line just like .Include( or .Select( would.

public static IQueryable<T> LoadNavigationProperty(this IQueryable<T> query, Expression<Func<T, object>>[] navigationProperties)
{
    if ((query != null) && (navigationProperties != null))
    {
        foreach (var navigationProperty in navigationProperties)
        {
            query = query.Include<T, object>(navigationProperty);
        }
    }

    return query;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top