开发者

EF - Why doesn't Include work on Properties

So I have classes that looks like this.

public class User {
    public virtual IList<Member> Members {get;set;}
}

public class Member {
    public virtual AnotherTable Another {get;set;}
}

public class AnotherTable {
    public string Name {get;set;}
}

When I perform the query directly against the DataContext the Include works, but when I do an AsQueryable() on the IList of members the include doesn't work.

Is there a way to have Include/Eager functionality on lazy loaded properties, such as the Members property above, or do I always have to go through the DataContext to get that feature?

User.Members.AsQueryable().Include(a => a.Another).ToList() // <-- nada, no way Jose
_db.Members.Include(m => m.Another).ToList() // <-- all good in the neighborhood

I ask cause it can be a huge difference of 开发者_JAVA百科1 sql query vs. 100 queries for something result equivalent.

Thanks in advance.


AsQueryable doesn't make it linq-to-entities query. It is still Linq-to-object query on top of List. List doesn't know how to handle Include - only DbQuery knows it so you must get DbQuery:

var entry = context.Entry(user);
entry.Collection(u => u.Member).Query().Include(m => m.Another).Load();


You'll have to go through the DbContext in order for Include() to work. You could abstract it into a Repository, but you'll still need to pass your Include() expression to your underlying context.

    private IQueryable<T> GetQuery<T>(params Expression<Func<T, object>>[] includeProperties) where T : class
    {
        IQueryable<T> query = _db.Set<T>();

        if (includeProperties != null)
        {
            foreach (Expression<Func<T, object>> expression in includeProperties)
            {
                query = query.Include(expression);
            }
        }

        return query;
    }


I also faced same problem.

I solved this just adding the reference System.Data.Entity & use following namespace:

   using System.Data.Entity;

You can try with it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜