如何使用 Linq to Entity 查询 C# windows Forms 应用程序中相关 table 中按字段排序的结果?

How to use Linq to Entity to query results ordered by field in related table in C# windows Forms application?

我在 SQL 服务器数据库中有 2 个表:

Table1:
  CustomerID
  CustomerName
Table2:
  TicketID
  TicketDate
  CustomerID

使用一个(表 1)到多个(表 2)相关

我想使用 C# 对实体查询进行 linq 查询,以查询按 TicketDate 降序排列的所有客户,这样我就可以在组合框中列出所有不同的客户名称,最近查看过票的客户位于顶部

我不是 100% 确定你想要什么,这是你要找的吗?

using (DatabaseEntities entities = new DatabaseEntities())
{
    //Gets a list of all customers, sorted by ticket date
    List<Table1> customers = entities.Table1
    .OrderByDescending(x => x.Table2.Select(y => y.TicketDate).OrderByDescending(y => y.TicketDate)
    .FirstOrDefault().TicketDate)
    .ToList();
}

假设 Table2 的记录数不是 Customer 的 10 倍以上,您可以改变一些事情。 OrderBy 工单和 select 客户

//Gets a list of all customers, sorted by ticket date
List<Table1> customers = entities.Table2
.OrderByDescending(t => t.TicketDate)
.Select(t => t.Table1)
.Distinct()
.ToList();

如果 Table2 有更多的记录(记录数的 10 倍以上或仅十亿),您应该从 Customer 开始并使用 Max date,因此对数据库的查询执行相同的操作并且不执行精确的为每个客户重新订购。

 List<Table1> customers = entities.Table1
.OrderByDescending(c => c.Table2.Max(t => t.TicketDate))
.ToList();

编辑

我认为这是您应该使用的选项,因为它不会导致每个记录的子查询来确定 MAX,而是对每个组执行 MAX

List<Table1> customers = entities.Table2
.GroupBy(t => t.Table1)
.OrderByDescending(g => g.Max(t => t.TicketDate))
.Select(g => g.Key)
.ToList();