2011-03-14 52 views
0

我在數據庫中有兩個表SQL Server的加入/子選擇的問題

Team:Id(int PK), Name(nvarchar) 

Player:Id(int PK), Name(nvarchar), Age(int), TeamId(int FK) 

我也有以下類

class Team 
{ 
    public int Id{get;set;} 
    public string Name{get;set;} 
} 

class Player 
{ 
    public int Id{get;set;} 
    public string Name{get;set;} 
    public int Age{get;set;} 
    public int TeamId{get;set;} 
} 

class TeamInfo 
{ 
    public Team Team{get;set;} 
    public List<Player> Players{get;set;} 
} 

我想從一個DATABSE提取List<TeamInfo>。 我使用的Ado.net,沒有EF或LINQ2SQL ...我問問什麼是最好的方式來查詢數據庫?

現在我得到所有的球隊,並且我爲每個球隊查詢桌上球員加入但肯定它不是最好的方式。

回答

0

你應該join查詢讀取數據庫中的所有信息:

SELECT 
     Team.Id as TeamId, 
     Team.Name as TeamName, 
     Player.Id as PlayerId, 
     Player.Name as PlayerId, 
FROM Team INNER JOIN Player on Team.Id = Player.TeamId 

使用此查詢作爲SqlCommand的一部分,並獲取數據到DataTable。然後:

var teamInfos = datatable.Rows 
        .Cast<DataRow>() 
        .GroupBy(dr => (int) dr["TeamId"]) 
        .Select(t => new TeamInfo 
         { 
          Team = new Team{ Id = t.Key, 
              Name = (string)t.First["TeamName"] }, 
          Players = t.Select(p => new PlayerInfo { 
             Id = (int)p["PlayerId"], 
             Name = (int)p["PlayerName"], 
             // other player fields here 
           }) 
           .ToList() 
         }); 

注:也許你需要一個LEFT而不是INNER這裏加入,因爲你不會沒有玩家獲得球隊並非如此。

1

我想創建與參數的SQL服務器的SP @teamid,然後執行該SP爲球隊並獲得玩家信息

create procedure [dbo].[TeamPlayers] 
as 

@teamid int 
begin 

    set nocount on; 

select 
    t.ID as TeamID, 
    t.name, 
    p.ID as PlayerID, 
    p.name, 
    p.age 
from dbo.Player p 
    inner join Team t 
     on p.TeamID=t.ID 
where [email protected] 


end