What Pattern will solve this - fetching dependent record from database

Posted by tunmise fasipe on Programmers See other posts from Programmers or by tunmise fasipe
Published on 2012-08-27T23:13:32Z Indexed on 2012/08/28 3:51 UTC
Read the original article Hit count: 250

Filed under:

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.

What pattern is used to solve this and how?

© Programmers or respective owner

Related posts about programming-practices