通过EF核心过滤更改顺序的顺序包括

发布于 2025-01-20 12:21:21 字数 1553 浏览 0 评论 0原文

假设我有这些实体

public class User
{
    public int Id { get; set; }
    public string Code { get; set; }
    public ICollection<Translation> Translations { get; set; }
}

public class Translation
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Language { get; set; }
    
    public int UserId { get; set; }
    public User User { get; set; }
}

,下面的代码

Users
    .Include(u => u.Translations
                    .Where(t => t.Language == "en")
                    .OrderBy(t => t.Name))
    .OrderBy(u => u.Code);

将生成此 SQL 语句,

...
ORDER BY [u].[Code], [t].[Name]

我如何影响 ORDER BY 的顺序?

...
ORDER BY [t].[Name], [u].[Code]

我已经尝试过

Users
    .Include(u => u.Translations
                    .Where(t => t.Language == "en")
                    .OrderBy(t => t.Name)
                    .ThenBy(t => t.User.Code));

但是生成的 SQL 语句更详细(更多连接)。这是正确的做法吗?

UPDATE

Include(u => u.Translations.Where(t => t.Language == "en")) 过滤器将检索零个或最多一个对每个User进行翻译,以便可以将其显示在二维表格中。

输入图片这里的描述

上面的Code列属于User实体,而Name列属于Translation< /代码> 实体。该表可以先按名称排序,也可以先按代码排序。

Say I have these entities

public class User
{
    public int Id { get; set; }
    public string Code { get; set; }
    public ICollection<Translation> Translations { get; set; }
}

public class Translation
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Language { get; set; }
    
    public int UserId { get; set; }
    public User User { get; set; }
}

And the code below

Users
    .Include(u => u.Translations
                    .Where(t => t.Language == "en")
                    .OrderBy(t => t.Name))
    .OrderBy(u => u.Code);

will produce this SQL statement

...
ORDER BY [u].[Code], [t].[Name]

How can I influence the order of the ORDER BY as such?

...
ORDER BY [t].[Name], [u].[Code]

I have tried

Users
    .Include(u => u.Translations
                    .Where(t => t.Language == "en")
                    .OrderBy(t => t.Name)
                    .ThenBy(t => t.User.Code));

But the generated SQL statement is more verbose (more joins). Is this the correct way of doing it?

UPDATE

The Include(u => u.Translations.Where(t => t.Language == "en")) filter will retrieve zero or at most one Translation for each User so that it could be displayed in a two-dimensional table.

enter image description here

The column Code above belongs to the User entity while the column Name belongs to the Translation entity. The table could be sorted by Name first or by Code first.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文