39

我正在使用实体框架,但在此示例中找不到包含方法:

using(ArticleExtractorEntities db=new ArticleExtractorEntities())  
{
    Preference pref= db.Preferences.Include(  

在这里,我只找到带有参数(字符串路径)的函数,我没有找到任何其他重载,那么如何将 Include 与 lambda 表达式一起使用?

4

4 回答 4

97

它不在 System.Linq 中。添加

using System.Data.Entity
于 2012-06-29T09:42:19.660 回答
12

更新。对于那些寻找如何使用 .Include() 扩展您的 linq 查询的人

不再是:

using System.Data.Entity;

使用 netcoreapp1.0 它是:

using Microsoft.EntityFrameworkCore;
于 2016-12-07T21:11:53.587 回答
1

您可以按照此博客文章中所示实现它:

public static class ObjectQueryExtension
{
    public static ObjectQuery<T> Include<T>(this ObjectQuery<T> mainQuery, Expression<Func<T, object>> subSelector)
    {
        return mainQuery.Include(FuncToString(subSelector.Body));
    }
    private static string FuncToString(Expression selector)
    {
        switch (selector.NodeType)
        {
            case ExpressionType.MemberAccess:
                return ((selector as MemberExpression).Member as Reflection.PropertyInfo).Name;
            case ExpressionType.Call:
                var method = selector as MethodCallExpression;
                return FuncToString(method.Arguments[0]) + "." + FuncToString(method.Arguments[1]);
            case ExpressionType.Quote:
                return FuncToString(((selector as UnaryExpression).Operand as LambdaExpression).Body);
        }
        throw new InvalidOperationException();
    }
    public static K Include<T, K>(this EntityCollection<T> mainQuery, Expression<Func<T, object>> subSelector)
        where T : EntityObject, IEntityWithRelationships
        where K : class
    {
        return null;
    }
    public static K Include<T, K>(this T mainQuery, Expression<Func<T, object>> subSelector)
        where T : EntityObject
        where K : class
    {
        return null;
    }
}
于 2012-06-29T09:44:32.797 回答