IQueryable <t>。包括<t,object =“”>&gt;(表达式<func <t,object =“”>&gt;不工作</func <t,> </t,> </t>

时间:2014-02-22 23:01:21

标签: c# iqueryable navigation-properties

我正在尝试使用IQueryable Include方法加载导航属性,但是虽然表达式是正确的但我没有得到任何结果

这是代码

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);
        }
    }
}

我在查询上设置了一个断点。包括并检查了数据:

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

在单步执行包含行之后,我再次检查了查询值,发现它不包含导航属性

2 个答案:

答案 0 :(得分:8)

Include()不会更改query实例,它会返回新实例。您需要将其分配回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);
        }
    }
}

答案 1 :(得分:0)

Marcin解释了为什么它不起作用(.Include(确实修改了查询)但是我只想给你另一种方法,这样你就可以使用该方法作为扩展方法,因此它可以用于就像.Include(.Select(一样。

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;
}