Question

In my Entity Framework project, lazy loading is disabled and it want it to be disabled by default.

Up to now I've used to load foreign key values in case they're needed for further processing explictly with the Include() method.

However, whenever I put one of the objects which is holding a loaded foreign key object into another object, from the perspective of the outer object the foreign key seems to be null.

var teams = (from team in db.Teams.Include("Captain")
             orderby team.Name
             select new ExtendedTeam {
                Team = team
             }).AsEnumerable();
// teams.First().Customer.Captain is null though the Captain property was explictly included

How can I access the Captain property without disabling lazy loading at all? I'd prefer not to add a Captain property to the Extended Team class.

Was it helpful?

Solution

Your projection seems to be screwing up the Include.

I'm not sure where the "customer" variable came from, but if you need to do a projection like that you can do something similar to:

var teams = (from team in db.Teams
             orderby team.Name
             select new {
                 Team = team,
                 Captain = team.Captain,
             }).ToList(); // execute the query

That will give you an anonymous type of Customer and Captain. You can extract the data however you need to from that to populate your ExtendedTeam object.

Since I called ToList() on the query I have executed the query, and my anonymous object has the Team object and the Captain object. As a side effect of this, Entity Framework has also done a "fix-up" of the relationships. If you inspect the anonymous type Team property, you will notice that Captain is also populated in it. EF was smart enough to know that they were related and it did relationship fix-up on the Team objects. You can now process the results like so:

var extended = teams.Select(t => new ExtendedTeam { Team = t });

That should work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top