Ahmad Houri
Ahmad Houri

Reputation: 1207

I can't find "Include" method with lambda expression in Entity framework?

I am using entity framework and I can't find include method like in this example:

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

here i find only the function include with the parameter (string path) and I don't find any other overload so how can I use Include with lambda expression?

Upvotes: 39

Views: 18508

Answers (4)

Easton James Harvey
Easton James Harvey

Reputation: 1672

Update. For those looking how it extend your linq query with .Include()

No longer is it:

using System.Data.Entity;

With netcoreapp1.0 it is:

using Microsoft.EntityFrameworkCore;

Upvotes: 12

Darin Dimitrov
Darin Dimitrov

Reputation: 1038770

You could implement it 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;
    }
}

Upvotes: 1

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60493

it's not in System.Linq. Add

using System.Data.Entity

Upvotes: 98

Related Questions