按实体框架中的子表排序

Ian*_*ink 3 c# linq entity-framework

在我的 Linq 中,我访问了一个简单的主/明细表:

_db.Countries.Include(x=>x.People);
Run Code Online (Sandbox Code Playgroud)

我希望人们按姓氏排序,但是当我在 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
Run Code Online (Sandbox Code Playgroud)

Yul*_*dra 5

你可以这样做。

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
Run Code Online (Sandbox Code Playgroud)

即使Select只选择国家/地区,People匿名类型也会连接到每个国家/地区的 People 属性。

生成的 sql 将包括 order by 查询等。

ORDER BY [Project1].[Id] ASC, [Project1].[C1] ASC, [Project1].[Lastname] ASC
Run Code Online (Sandbox Code Playgroud)

聚苯乙烯

作为急切加载的解决方法,您可以做的是进行关系修复。使用这种方法只会有一次数据库往返,而不是先加载所有国家,然后加载每个人。

关系修复是 EF 将相关实体链接在一起的过程。例如,当已知的相关客户从数据库中具体化时,修复将设置订单的“客户”属性。一旦你理解了修复,你就可以利用它来做各种有趣的事情。- Alex D James 的实体框架术语