Reputation: 1061
I am exploring with Entity Framework Core and started off by using the code first approach while reading through this guide https://docs.efproject.net/en/latest/platforms/aspnetcore/new-db.html with the exception of different models.
In EF6 it had lazy loading and I was able to pull the related entities really easily but it is no working in EF Core. I was wondering how to get this working or if there is a work around to get it working.
Here is an example of what Two of my models look like:
public class Team
{
public string Id { get; set; }
public string Name { get; set; }
public string Icon { get; set; }
public string Mascot { get; set; }
public string Conference { get; set; }
public int NationalRank { get; set; }
public List<Game> Games { get; set; }
}
public class Game
{
public string Id { get; set; }
public string Opponent { get; set; }
public string OpponentLogo { get; set; }
public string GameDate { get; set; }
public string GameTime { get; set; }
public string TvNetwork { get; set; }
public string TeamId { get; set; }
public Team Team { get; set; }
}
I am wanting to get all of the Games for a Team but as of right now it is null.
I decided to make a Web Api project so I have a controller called TeamsController and when I make a GET request to the controller I want to get a list of Teams with the Games property populated with the related games.
Here is what I have tried:
[HttpGet]
public async Task<List<Team>> Get()
{
return await _context.Teams.Include(t => t.Games).ToListAsync();
}
This is the JSON result:
[
{
"id": "007b4f09-d4da-4040-be3a-8e45fc0a572b",
"name": "New Mexico",
"icon": "lobos.jpg",
"mascot": "New Mexico Lobos",
"conference": "MW - Mountain",
"nationalRank": null,
"games": [
{
"id": "1198e6b1-e8ab-48ab-a63f-e86421126361",
"opponent": "vs Air Force*",
"opponentLogo": "falcons.jpg",
"gameDate": "Sat, Oct 15",
"gameTime": "TBD ",
"tvNetwork": null,
"teamId": "007b4f09-d4da-4040-be3a-8e45fc0a572b"
}
]
}
]
When I do this:
[HttpGet]
public async Task<List<Team>> Get()
{
return await _context.Teams.ToListAsync();
}
I get all of the teams but the Games property is null.
I was hoping it would return all the teams in the database along with all of the games for each team. How can I get this working?
Upvotes: 4
Views: 644
Reputation: 499
Lazy loading is currently not implemented in entity framework core as indicated here, I suggest you to look at AutoMapper to project your desired results in POCO. Because what you want will exactly cause the n+1 problem.
Upvotes: 2