简体   繁体   English

在实体框架中按子表排序

[英]Order by child table in entity framework

In my Linq I access a simple master/detail table: 在我的Linq中,我访问一个简单的主/详细信息表:

_db.Countries.Include(x=>x.People);

I wish the People to be sorted by Lastname, but when I include a order by in the include it errors out with : 我希望人们按姓氏排序,但是当我在include中包含一个订单时,它会出错:

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

You can do this. 你可以这样做。

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

Even though Select only selects the Country, the People in anonymous type will connect to People property on each Country. 即使Select仅选择Country,匿名类型的People也将连接到每个Country上的People属性。

The generated sql will include the order by query like. 生成的sql将按查询顺序包含顺序。

ORDER BY [Project1].[Id] ASC, [Project1].[C1] ASC, [Project1].[Lastname] ASC

PS PS

As work around of eager loading, what you can do is doing relationship fix-up. 作为急切加载的解决方法,您可以做的就是进行关系修复。 There will only one database roundtrip using this approach instead of loading all countries first then load each people. 使用这种方法只会有一个数据库往返,而不是首先加载所有国家然后加载每个人。

Relationship Fix-up is the process by which the EF, links related Entities together. 关系修复是EF将相关实体链接在一起的过程。 For example fix-up will set the "Customer" property of an Order when a known to be related Customer is materialized from the database. 例如,当从数据库中实现已知的相关客户时,修订将设置订单的“客户”属性。 Once you understand fix-up you can leverage it to do all sorts of interesting things. 一旦你理解了修复,你就可以利用它来做各种有趣的事情。 - Entity Framework Jargon by Alex D James - Alex D James的实体框架术语

This is not supported. 这不受支持。 You could order the child collections on the client once the query is executed by looping through the countries collection retrieved from the database and ordering its People property. 通过循环访问从数据库检索的国家/地区集合并订购其People属性,您可以在执行查询后在客户端上对子集合进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM