【发布时间】:2018-05-31 23:45:33
【问题描述】:
我在一个结果中显示企业和人员,并希望将它们一起订购。
伪代码:
if business name is not null
order by business name
else
order by first name then last name
我构建了 LINQ 查询,它连接到多个表(并且工作正常),大致如下所示。
var query = from x in ...
join business in dbContext.Businesses on ...
from businesses in bus.DefaultIfEmpty()
join person in dbContext.People on ...
from people in peo.DefaultIfEmpty()
select new Party
{
person.FirstName,
person.LastName,
business.Name,
};
我不知道如何编写一个 LINQ 表达式,如果记录是企业,则仅按企业名称排序,否则人名和姓氏。我能得到的最接近的是以下内容,其中始终包括按人的姓氏排序(即使对于企业也是如此)。
var result =
whereQuery
.OrderBy(x => x.BusinessName != null ? x.BusinessName : x.PersonFirstName)
.ThenBy(x => x.PersonLastName);
转换成 SQL:
ORDER BY CASE
WHEN [business].[Name] IS NOT NULL
THEN [business].[Name]
ELSE [person].[FirstName]
END, [person].[LastName]
我想要的是:
ORDER BY CASE
WHEN [business].[Name] IS NOT NULL
THEN [business].[Name]
ELSE [person].[FirstName], [person].[LastName]
END
这是我希望能够写的(显然错误部分的语法不正确):
var result =
whereQuery
.OrderBy(x => x.BusinessName != null ? x.BusinessName : x.PersonFirstName, x.PersonLastName);
从技术上讲,它并没有太大的区别(如果是企业,则人名和姓氏将为空,因此不应该影响顺序)。但 SQL 仍会尝试通过它不需要做的事情进行排序。
【问题讨论】:
标签: c# linq .net-core entity-framework-core