I have the NFL season schedule saved in an SQL Server DB. A Game table has fields of Week (referring to the week of the season in which the game takes place [1-17]), AwayTeamID, and HomeTeamID, among others. The AwayTeamID and HomeTeamID fields are foreign keys referencing the Team table. I want to use a LINQ statement (within an ASP.NET MVC 3 app) to return games by week, including team names from the Team table. I know at least one way to do this, but specifically (and I’m hoping more elegantly), I’d like return a result that has each week associated with a sequence of games that correspond to that week, instead of a returning a sequence of new { Game, AwayTeam, HomeTeam } objects and then drilling into the Game item to get the week. I’m not sure I’ve made my goal clear…if not, let me know and I’ll try to clarify.
I read on 101 LINQ Samples about something similar using the into keyword within a join statement so that the result would be a sequence of weeks, each associated with its own sequence of games. Using the example from that site, I tried the following:
string[] wks = { "1", "2", "3" };
var model =
from g in _db.NFLGames
join a in _db.NFLTeams on g.AwayTeamID equals a.NFLTeamID
join h in _db.NFLTeams on g.HomeTeamID equals h.NFLTeamID
select new TestGameModel { Game = g, AwayTeam = a.Name, HomeTeam = h.Name };
var weekgames =
from w in wks
join gm in model on w equals gm.Game.NFLWeek into gw
select new TestNflWeeklySchedule { Week = w, Games = gw };
foreach (var wg in weekgames) {
System.Diagnostics.Debug.WriteLine("NFL week: " + wg.Week + " number of games this week: " + wg.Games.Count());
foreach (var g in wg.Games) {
System.Diagnostics.Debug.WriteLine(" " + g.AwayTeam + " at " + g.HomeTeam + " [" + g.Game.DateTimeStart + "]");
}
}
The code executes, but the output is
NFL week: 1 number of games this week: 0
NFL week: 2 number of games this week: 0
NFL week: 3 number of games this week: 0
Apparently, the second query joining the model is not matching the games that occur in the designated week. I’ve also tried, instead of two queries, just one LINQ statement, which essentially nests the first query within the second. That gave me the same result.
Can anyone tell me what error I have in my code or why this is not working? I’m new to LINQ, so there’s a good chance it’s something simple.
Is this what you’re looking for?