tags:

views:

25

answers:

3

I have a table called Game, which holds 4 columns for player id's. And I also have a table called Player. When I try to count all the games in which a player has been in, I only get the players from the first column in the Game table.

player.Games.Count();

I have set up foreign keys for all the tables, and it's showing up correctly in the table designer. From the image below, you can see that it should count from blue1+2 and red1+2, but it only counts from Blue1...

alt text

I also tried to create a method to manually select all the games:

public int GetPlayerGames(int playerID)
{
    return (from game in db.Games
            where game.Blue1 == playerID
            || game.Blue2 == playerID
            || game.Red1 == playerID
            || game.Red2 == playerID
            select game).Count();
}

But when I use it inside a linq query

return from player in db.Players
       where GetPlayerGames(player.ID) > 0
       select player;

I get this error:
Method 'Int32 GetPlayerGames(Int32)' has no supported translation to SQL.

+1  A: 

If you've set up four relationships they'll each have a different name, most likely Games, Games1, Games2 and Games3. By doing player.Games.Count() you're only counting the games associated with the first relationship, you need to add extra counts for the games associated by the other relationships:

var allGameCounts = player.Games.Count() + player.Games1.Count() + player.Games2.Count() + player.Games3.Count();
Dave
A: 

I actually ended up using the method above, but just casting it to a list first:

return from player in db.Players.ToList()
       where GetPlayerGames(player.ID) > 0
       select player;
peirix
Make sure you are aware of the consequences of "just casting it to a list" though. Calling db.Players.ToList() goes to the database and fetches the entire database table into memory, then applies the filtering afterwards, in code. That's probably not what you want: it won't scale well when the number of Players gets large...
Alex York
Yup. I know. For now, I'm fairly sure the list won't exceed 20 players. But you're absolutely right, it won't scale well. So until I find a good way to write methods that linq understand, I'll just keep it this way, while keeping in mind that I will have to refactor at a later point.
peirix
A: 

If you want to do the filtering in sql without loading the whole database, you could do this...

from player in db.Players
where player.Games.Any()
  || player.Games1.Any()
  || player.Games2.Any()
  || player.Games3.Any()
select player
David B