I have these classes
class Match
{
int MatchID,
int TeamID, //used to reference Team
... other fields
}
Note: Match actually have 2 teams which means 2 TeamID
class Team
{
int TeamID,
string TeamName
}
In my view I need to display List<Match> showing the TeamName. So I added another field
class Match
{
int MatchID,
int TeamID, //used to reference Team
... other fields
string TeamName;
}
I can now do
Match m = getMatch(id);
m.TeamName = getTeamName(m.TeamId); //get name from database
But for a List<Match>, getTeamName(TeamId) will go to the database to fetch TeamName for each TeamID.
For a page of 10 Matches per page, that could be (10x2Teams)=20 trip to database.
To avoid this, I had the idea of loading everything once, store it in memory and only lookup the TeamName in memory. This made me have a rethink that what if the records are 5000 or more.
Is there a better approach for this? Thanks.
Peform your caching per page – put together a list of ids that exist in your current list of 10 matches, and then load up all teams that have one of those ids.
You don’t say how you are accessing your data, but if you are using SQL, then IN is your friend.
Alternatively, you could load up the team with your match in the first place, using a join statement, and then populate the team data at the same time you populate the match data.