Linq To Entities - 如何过滤子实体 [英] Linq To Entities - how to filter on child entities
问题描述
我有实体 Group
和 User
.Group
实体具有 Users
属性,它是一个用户列表.
用户有一个名为 IsEnabled
的属性.
I have entities Group
and User
.
the Group
entity has Users
property which is a list of Users.
User has a property named IsEnabled
.
我想编写一个 linq 查询,它返回一个 Group
的列表,它只包含 IsEnabled
为 true 的 User
.
I want to write a linq query that returns a list of Group
s, which only consists of User
s whose IsEnabled
is true.
例如,对于像下面这样的数据AllGroups
A组
用户 1 (IsEnabled = true)
用户 2 (IsEnabled = true)
用户 3(IsEnabled = false)
so for example, for data like below
AllGroups
Group A
User 1 (IsEnabled = true)
User 2 (IsEnabled = true)
User 3 (IsEnabled = false)
B组
用户 4 (IsEnabled = true)
用户 5 (IsEnabled = false)
用户 6(IsEnabled = false)
Group B
User 4 (IsEnabled = true)
User 5 (IsEnabled = false)
User 6 (IsEnabled = false)
我想要过滤组
A组
用户 1 (IsEnabled = true)
用户 2(IsEnabled = true)
I want to get
FilteredGroups
Group A
User 1 (IsEnabled = true)
User 2 (IsEnabled = true)
B组
用户 4(IsEnabled = true)
Group B
User 4 (IsEnabled = true)
我尝试了以下查询,但 Visual Studio 告诉我
[无法分配属性或索引器用户"——它是只读的]
I tried the following query, but Visual Studio tells me that
[Property or indexer 'Users' cannot be assigned to -- it is read only]
FilteredGroups = AllGroups.Select(g => new Group()
{
ID = g.ID,
Name = g.Name,
...
Users = g.Users.Where(u => u.IsInactive == false)
});
感谢您的帮助!
推荐答案
我设法通过颠倒查询来做到这一点:
I managed to do this by turning the query upside down:
var users = (from user in Users.Include("Group")
where user.IsEnabled
select user).ToList().AsQueryable()
from (user in users
select user.Group).Distinct()
通过使用 ToList(),您可以强制往返数据库,这是必需的,否则会妨碍延迟执行.第二个查询仅对检索到的数据重新排序.
By using the ToList() you force a roundtrip to the database which is required because otherwise the deferred execution comes in the way. The second query only re-orders the retrieved data.
注意:之后您可能无法更新您的实体!
这篇关于Linq To Entities - 如何过滤子实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!