简体   繁体   中英

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM