0
var x = connection.Set<Team>() .Include(t => t.Level) .Select(t => new {Team = t, LevelForTesting = t.Level}) .ToList() 

Why I don't get the object x[0].Team.Level (I have 'null') but get the object x[0].LevelForTesting? How can I change this code to get x[0].Team.Level? Thanks.

1 Answer 1

2

You are throwing away the results of your eager loading by the anonymous select. Just drop the select and you will be able to access the Level in your list of Team:

var x = connection.Set<Team>().Include(t => t.Level).ToList(); var level = x[0].Level; 

To get a better understanding of lazy/eager loading you should read this. Basically eager loading populates the specified navigation properties of your list of entities.

Sign up to request clarification or add additional context in comments.

8 Comments

Unfortunately, I can't to remove anonymous layer because in the real code I have a more complex query that use the specific projection type.
Then you can't make use of eager loading. But what you're trying to do has the same effect with the projection, for every object instead of accessing the level through Team, you access it through the anonymous type? var level = x[0].LevelForTesting; Doesn't really make that much of a difference in my opinion.
var qry = connection.From<Team>().Select(t => new LevelSummaryCollectionItem() {Team = t}); var teamCondition = GetTeamCondition(); if (teamCondition != null) qry = qry.Where(teamCondition); qry = qry.OrderBy(t => t.Team.Level.Id); var teamList = qry.Select(t => new { t.Team, t.Team.Level //instead .Include() }).ToList(); As I remember early this code worked fine, but now I got 'null' in the t.Team.Level. So I'm looking for the easiest solution to fix
@Serg046 It probably worked before because of lazy loading (which executes another query when you try to access the Team). Did you by any chance remove the virtual keyword for Team or disabled lazy loading/proxy creation specifically in your dbcontext?
@Serg046 In your Team model add virtual to the property: public virtual Level Level { get; set;}, then you can make use of lazy loading again.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.