如何在数据库层面基于LocalizationType对EntityA列表按本地化国名排序?
问题描述
给定以下实体关系:
class EntityA { public Country DestinationCountry { get; set; } } class Country { public string CountryCode { get; set; } public IList<CountryLocalization> Localizations { get; set; } = new List<CountryLocalization>(); } public class CountryLocalization { public string CountryCode { get; set; } public Country Country { get; set; } public CountryLocalizationType LocalizationType { get; set; } public string CountryName { get; set; } }
每个EntityA对应一个DestinationCountry,每个Country拥有不同语言的多份本地化信息(例如某EntityA的目标国家有两种语言的译文)。请问能否通过指定LocalizationType,对EntityA列表按本地化国家名称排序?用户给出的示例查询代码如下:
IQueriable<EntityA> query = query.OrderBy(a => a.Where(b => b.DestinationCountry.Localizations.Where(l => l.LocalizationType == ENG)) ...
解决方案
可以实现,不过你给出的示例代码存在语法错误(a是EntityA实例,并非集合,不能调用Where方法),正确的写法需要定位到对应LocalizationType的CountryLocalization条目,再取其CountryName作为排序依据。
以筛选LocalizationType.ENG为例,正确的IQueryable排序代码如下:
var targetLocalizationType = CountryLocalizationType.ENG; IQueryable<EntityA> sortedQuery = query.OrderBy(a => a.DestinationCountry.Localizations .FirstOrDefault(l => l.LocalizationType == targetLocalizationType)?.CountryName );
关键说明:
- 使用
FirstOrDefault可以避免因部分Country缺少目标类型本地化条目而抛出异常,此时缺失条目的CountryName会取null,通常会排在排序结果的末尾。如果能确保所有Country都存在目标类型的本地化,也可以用SingleOrDefault或直接First。 - 该写法在EF Core等ORM框架中会被正确转换为SQL语句,通过关联查询筛选出对应本地化类型的国家名称后完成排序。
- 若需降序排序,替换
OrderBy为OrderByDescending即可。
内容的提问来源于stack exchange,提问作者GeorgeR
相关产品推荐
相关产品推荐

