I have a WebAPI controller that needs to return a collection from the database but I also need to remove some properties from some of the entities. However, for some reason the properties representing another entity returns null except for sometimes when I am stepping over the code in debug mode. I have shown the json response below which shows Sport, HomeTeam and AwayTeam as null:
But when I step over the code in debug mode I get the expected result:
The relevant controller method is as follows
public dynamic Get()
{
var allPicks = _db.Picks;
if (User.Identity.IsAuthenticated)
{
string userId = User.Identity.GetUserId();
var picks = _db.UnlockedPicks
.Include(p => p.SelectedPick.AwayTeam)
.Include(p => p.SelectedPick.HomeTeam)
.Include(p => p.SelectedPick.Sport)
.Where(p => p.UserId == userId);
var unlockedPicks = picks.Select(p => p.SelectedPick);
var otherPicks = allPicks.Except(unlockedPicks).Select(p => new
{
Analysis = "",
PickSummary = "",
Title = p.Title,
Id = p.Id,
Sport = p.Sport,
HomeTeam = p.HomeTeam,
AwayTeam = p.AwayTeam,
MatchTime = p.MatchTime,
PublishTime = p.PublishTime
});
return new
{
UnlockedPicks = unlockedPicks.OrderByDescending(p => p.MatchTime),
OtherPicks = otherPicks.OrderByDescending(p => p.MatchTime)
};
}
var publicPicks = allPicks.OrderByDescending(p => p.MatchTime).Select(p => new
{
Analysis = "",
PickSummary = "",
Title = p.Title,
Id = p.Id,
Sport = p.Sport,
HomeTeam = p.HomeTeam,
AwayTeam = p.AwayTeam,
MatchTime = p.MatchTime,
PublishTime = p.PublishTime
});
return new { UnlockedPicks = new Pick[0], OtherPicks = publicPicks };
}
Without the Include()
it returned null every time but how can I make it return the expected result every time?
It happens because you are not using lazy loading. When lazy loading is deactivated, you have to call Include
in order to load the navigation properties. If you want load all navigation properties, without calling Include
, will have to activate the lazy loading, which can be done through the context's constructor. Like this:
public partial class SchoolDBEntities : DbContext
{
public SchoolDBEntities(): base("name=SchoolDBEntities")
{
this.Configuration.LazyLoadingEnabled = true;
}
}
The lazy loading should be activated by default. You probably have deactivated it somewhere else in your code. It is also called automatically every time you inspect a navigation property in debug mode.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments