C# 实体框架中的按子表排序
在我的Linq中,我访问一个简单的主/明细表:C# 实体框架中的按子表排序,c#,linq,entity-framework,C#,Linq,Entity Framework,在我的Linq中,我访问一个简单的主/明细表: _db.Countries.Include(x=>x.People); 我希望按姓氏对人员进行排序,但当我在include中包含order by时,会出现以下错误: The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties
_db.Countries.Include(x=>x.People);
我希望按姓氏对人员进行排序,但当我在include中包含order by时,会出现以下错误:
The Include path expression must refer to a navigation property defined on the type.
Use dotted paths for reference navigation properties and the Select operator for collection navigation properties. Parameter name: path
这是不受支持的。执行查询后,您可以通过循环从数据库检索的countries集合并对其People属性进行排序,在客户端上对子集合进行排序。您可以这样做
var countries = _db.Countries
.Select(c => new
{
Country = c,
People = c.People.OrderBy(p => p.Lastname)
})
.AsEnumerable() // not execute yet
.Select(a => a.Country)
.ToArray(); // execute
即使Select
仅选择国家/地区,匿名类型的People
将连接到每个国家/地区的People属性
生成的sql将包括order by查询,如
ORDER BY [Project1].[Id] ASC, [Project1].[C1] ASC, [Project1].[Lastname] ASC
PS
作为快速加载的解决方案,您可以做的是修复关系。使用这种方法,只有一个数据库往返,而不是先加载所有国家,然后加载每个人
关系修复是EF、链接相关的过程
实体在一起。例如,修复将设置“Customer”属性
当一个已知的相关客户从
数据库。一旦您了解了修复,您就可以利用它来完成所有工作
各种有趣的事情