我使用Entity Framework并将此实体映射:
Parent
- Child 1 (ActiveInd = "Y")
- Child 2 (ActiveInd = "N")
- Child 3 (ActiveInd = "Y")
我想要一个类似于此的Linq查询(但是可以工作的一个:)
Parent parent = (from p in DataContext.Current.Parents
where p.ParentId == _parentId
&& p.Children.Active == true select p).FirstOrDefault();
它应该返回以下内容(只有活动记录):
Parent
- Child 1 (ActiveInd = "Y")
- Child 3 (ActiveInd = "Y")
答案 0 :(得分:2)
如果您希望父母至少有一个活跃的孩子:
from p in DataContext.Current.Parents
where p.ParentId == _parentId && p.Children.Any(c => c.Active)
select p
如果您希望父母拥有所有活跃的孩子:
from p in DataContext.Current.Parents
where p.ParentId == _parentId && p.Children.All(c => c.Active)
select p
如果您想要将子项过滤为同一查询的一部分,您可以执行以下操作:
from p in DataContext.Current.Parents
where p.ParentId == _parentId
select new { Parent = p, ActiveChildren = p.Children.Where(c => c.Active) } into parentWithActiveChildren
where parentWithActiveChildren.FilteredChildren.Any()
select parentWithActiveChildren
或
from p in DataContext.Current.Parents
where p.ParentId == _parentId && p.Children.Any(c => c.Active)
select new { Parent = p, ActiveChildren = p.Children.Where(c => c.Active) }