【问题标题】:Linq , orderBy , and includeLinq 、 orderBy 和包括
【发布时间】:2020-09-04 05:45:48
【问题描述】:

我与这三个实体有一对多的关系:

class Tournamnet{
int Id 
string Name 
ICollection Games<Game>
},

class Game{
int Id 
int TournamentId
ICollection PlayerGames<PlayerGame>
}

class PlayerGame{
int Id
int GameId
int PlayerId
bool IsWinner
}

我想以 JSON 格式获取有关锦标赛的所有数据,

        public Tournament GetById(int id)
        {
            var tournament = tournamentTable
                .Include(tournament => tournament.Game)
                .ThenInclude(game => game.PlayerGame)
                .FirstOrDefault(x => x.Id == id);


            return tournament;
        }

这是我的查询,这里每个锦标赛都有一个游戏集合,每个游戏都有两个 PlayerGames,一个 IsWinner = true,另一个 IsWinner = false,我需要按 GameId 排序 PlayerGames,我该如何解决... ?

【问题讨论】:

    标签: .net linq asp.net-core


    【解决方案1】:

    我需要通过 GameId 订购 PlayerGames,我该如何解决...?

    首先确保 PlayerGames 是一个可以排序的集合类型。

    例如

    IList<PlayerGame> PlayerGames {get;set;} = new List<PlayerGame>()
    

    然后从数据库中取出后进行排序。

    t.PlayerGames = t.PlayerGames.OrderBy(g => g.GameId).ToList();
    

    或者,您可以创建一个自定义的 ICollection 实现,该实现始终按 T 的属性之一排序,但没有内置的,这似乎工作太多。

    【讨论】:

    • 虽然通常在数据库中排序更好,但在这种情况下并不简单。 EF 为包含(尤其是多个包含)生成 SQL 的方式使得在查询中指定排序变得困难,并且可能代价高昂。
    猜你喜欢
    • 2012-07-25
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 2011-05-29
    • 1970-01-01
    • 2017-06-12
    相关资源
    最近更新 更多