Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

c# - How does LINQ expression syntax work with Include() for eager loading

I have a query below, but I want to perform an Include() to eager load properties. Actions has a navigation property, User (Action.User)

1) My basic query:

from a in Actions
join u in Users on a.UserId equals u.UserId
select a

2) First attempt:

from a in Actions.Include("User")
join u in Users on a.UserId equals u.UserId
select a

But Action.User is not populated.

3) Try to eager load 'User' into the navigation property in action outside of query:

(from a in Actions
join u in Users on a.UserId equals u.UserId    
select a).Include("User")

In LINQPad trying Include's I get an error:

'System.Linq.IQueryable' does not contain a definition for 'Include' and no extension method 'Include' accepting a first argument of type 'System.Linq.IQueryable' could be found (press F4 to add a using directive or assembly reference)

I think this is because LINQ doesn't support Include().

So I tried in VS; query 2 runs, but returns unpopulated User property. Query 3 the extension method does not seem to exist, although it does exist on Action itself without the query.

question from:https://stackoverflow.com/questions/6761104/how-does-linq-expression-syntax-work-with-include-for-eager-loading

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I figured it out, thanks for the suggestions anyway. The solution is to do this (2nd attempt in my question):

var qry = (from a in Actions
join u in Users on a.UserId equals u.UserId    
select a).Include("User")

The reason intellisense didn't show Include after the query was because I needed the following using:

using System.Data.Entity;

Everything worked fine doing this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...