gpt4 book ai didi

c# - 按 Entity Framework 中的子表排序

转载 作者:行者123 更新时间:2023-11-30 14:29:33 27 4
gpt4 key购买 nike

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

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

我希望人们按姓氏排序,但是当我在包含中包含顺序时,它会出错:

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

最佳答案

你可以做到这一点。

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 query 之类的。

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

附言

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

Relationship Fix-up is the process by which the EF, links related Entities together. 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

关于c# - 按 Entity Framework 中的子表排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25713058/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com