如何将以下 Linq 查询压缩为一个 IQueryable
我有一个 EntityFramework 模型,其中包含具有组织 EntityCollection 的用户实体。
对于特定用户,我尝试编写一个 Linq 查询来返回该用户所属组织的名称,其中该查询只会访问数据库一次。
我的问题是,我无法了解如何编写此查询,而不必先具体化用户,然后查询用户组织集合。
我想尝试编写一个查询数据库一次的查询。
到目前为止我所拥有的:
var orgNames = context.Users
.Where(u => u.LoweredUserName == userName.ToLower())
//materialises user
.FirstOrDefault()
.Organisations
//second hit to the db
.Select(o => o.Name);
我的伪目标是什么,但只见树木不见森林:
orgNames = context.Users
.Where(u => u.LoweredUserName == userName.ToLower())
//don't materialise but leave as IQueryable
.Take(1)
//The problem: turn what the query sees as possibly multiple
// (due to the Take method) EntityCollection<Organisation> into a List<String>
.Select(u => u.Organisations.Select(o => o.Name));
我看过聚合体,但我似乎在兜圈子:)
I have an EntityFramework model that has User entity that has an EntityCollection of Organisations.
For a particular User I am trying to write a Linq Query to return the names of the organisations that the user belongs where that query will hit the db only once.
My problem is that I cannot see how to write this query without having to materialise the user first then query the users organisation collection.
I would like to try and write one query that hits the db once.
What I have so far:
var orgNames = context.Users
.Where(u => u.LoweredUserName == userName.ToLower())
//materialises user
.FirstOrDefault()
.Organisations
//second hit to the db
.Select(o => o.Name);
What I was psuedo aiming for but cannot see the wood for the trees:
orgNames = context.Users
.Where(u => u.LoweredUserName == userName.ToLower())
//don't materialise but leave as IQueryable
.Take(1)
//The problem: turn what the query sees as possibly multiple
// (due to the Take method) EntityCollection<Organisation> into a List<String>
.Select(u => u.Organisations.Select(o => o.Name));
I have looked at aggregates but I seem to be going in circles :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
哎哟!我想我可以通过使用 SelectMany 将集合的集合压缩为一个集合来回答我自己的问题,如下所示:
Doh! I think I can answer my own question by using SelectMany to condense the Collection of Collections into one collection like so:
我假设 Lowered User name 是唯一的,否则查询将毫无意义,因此您可以使用。
I'm assuming that Lowered User name is unique, otherwise the query would be fairly meaningless, so you can just use.