【问题标题】:Query multiple many-to-many relationship with linq c#用linq c#查询多个多对多关系
【发布时间】:2017-05-06 03:07:51
【问题描述】:

我的数据库 Game、Role 和 Player 中有三个表。在游戏和角色之间,我在角色和玩家之间有多对多的关系。我在 Game 和 Player 之间也有一对多的关系。我使用实体框架来映射我的表。 我想要实现的是让所有玩家都在特定的游戏 ID 和角色 ID 下。

    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;
        }
    }

【问题讨论】:

  • 您需要播放器或游戏吗?
  • int 不能为空...
  • 我有可选参数,这是我让它工作的唯一方法:)
  • 如果你让 int 可以为空,就像 int? 一样,它可以为空。当然,这可能会带来其他变化。
  • 请您澄清问题是什么以及您要达到什么目的,您的解释和代码告诉我们两个不同的事情

标签: c# entity-framework linq many-to-many


【解决方案1】:

虽然您需要玩家,但您的代码说明了另一件事。如果您需要游戏,可以使用导航属性构建以下查询:

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();
}

【讨论】:

    猜你喜欢
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    相关资源
    最近更新 更多