Linq To Entities - 如何过滤子实体 [英] Linq To Entities - how to filter on child entities
问题描述
我有实体组
和用户
。
组
实体具有用户
属性,它是用户列表。
用户具有名为 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查询,返回一个组列表
s,它只包含用户
s,其 IsEnabled
为true。
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)
我想要得到
FilteredGroups
A组
用户1(IsEnabled = true)
用户2(IsEnabled = true)
I want to get
FilteredGroups
Group A
User 1 (IsEnabled = true)
User 2 (IsEnabled = true)
用户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.
注意:以后您可能无法udpate您的实体!
Note: You might not be able to udpate your entities afterwards!
这篇关于Linq To Entities - 如何过滤子实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!