【问题标题】:I can't find "Include" method with lambda expression in Entity framework?我在实体框架中找不到带有 lambda 表达式的“包含”方法?
【发布时间】:2012-06-29 09:41:20
【问题描述】:

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

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

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

【问题讨论】:

  • 您需要使用 EF 4 .1 或更高版本。请注意,VS 2010 附带的是 EF 4,它没有有这个。

标签: c# .net entity-framework


【解决方案1】:

它不在 System.Linq 中。 添加

using System.Data.Entity

【讨论】:

  • @ahmadhori 你在 linq to entity 还是 linq to sql 中?
  • 自最新更新以来,已被移动。如果您已经升级了框架,请在下面查看我的回答。
【解决方案2】:

更新。对于那些希望使用 .Include() 扩展您的 linq 查询的人

不再是了:

using System.Data.Entity;

使用 netcoreapp1.0 是:

using Microsoft.EntityFrameworkCore;

【讨论】:

  • 这不仅适用于那些使用“EF Core?”的人。 (或“.Net Core”,如果你愿意的话)
【解决方案3】:

你可以实现它as shown in this blog post:

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

【讨论】:

    【解决方案4】:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-09
    • 2023-03-07
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多