2017-05-05 61 views
0

我有三個表在我的數據庫遊戲,角色和播放器。在遊戲和角色之間我有角色和玩家之間的多對多關係。我在遊戲和玩家之間也有一對多的關係。我已經使用實體框架來映射我的表格。 我想要實現的是讓所有玩家在特定的gameID和roleID下玩。查詢與linq c的多對多關係#

public IList<Game> GetGamesRolePlayer(int? gameID, int? roleID) 
    { 

     using (DbContextdb = new DbContext()) 
     { 
      db.Configuration.ProxyCreationEnabled = false; 

      if (gameID.HasValue && !roleID.HasValue) 
      { 
       var query1 = (from g in db.Game.Include(r => r.Role) 
           where g.ID == gameID 
           select g).ToList(); 
       _games = query1; 
       return _games; 

      } 
      if (gameID.HasValue && roleID.HasValue) 
      { 
       var query2 = (from g in db.Game 
           from r in db.Role.Include(p => p.Player) 
           where g.ID == game && r.ID == roleID 
           select g).ToList(); 
       _games = query2; 
       return _games; 
      } 
      var query = from game in db.Game select game; 
      _games = query.Include(r => r.Role).ToList(); 
      return _games; 
     } 
    } 
+1

您需要玩家或遊戲嗎? – octavioccl

+0

int不能爲空... –

+0

我有可選參數,這是我可以使它工作的唯一方法:) –

回答

0

我雖然你需要的球員,但你的代碼告訴另一件事。如果您需要遊戲,可以使用導航屬性構建以下查詢:

using (DbContextdb = new DbContext()) 
{ 
     db.Configuration.ProxyCreationEnabled = false; 
     IQueryable<Game> query=db.Game.Include(g=>g.Roles); 

     if (gameID.HasValue) 
      query=query.Where(g=>g.ID==gameID.Value) 

     if (roleID.HasValue) 
      query=query.Include(g=>g.Roles.Select(r=>r.Players)) 
         .Where(g=>g.Roles.Any(r=>r.ID==roleID.Value)) 

     return query.ToList(); 
}