[英]Query multiple many-to-many relationship with linq c#
I have three tables in my database Game, Role and Player. 我的数据库游戏,角色和玩家中有三个表。 Between Game and Role I have a many to many relationship and between Role and Player.
在游戏与角色之间,我与角色与玩家之间存在多对多关系。 I also have a one to many relationship between Game and Player.
我在Game和Player之间也有一对多的关系。 I have used Entity Framework to map my tables.
我已经使用实体框架来映射我的表。 What I am trying to achieve is to get all the players under specific gameID and roleID.
我要实现的目标是让所有玩家都拥有特定的gameID和roleID。
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;
}
}
I though you need the players but your code is telling another thing. 我虽然您需要播放器,但是您的代码却告诉了另一件事。 If you need the games,you can build the following query using navigation properties:
如果您需要游戏,则可以使用导航属性构建以下查询:
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.