Dav*_*veo 1 linq linq-to-entities entity-framework-4
如何对父子关系进行急切查询:
如果我试试
from p in _context.Parents.Include("children")
join c in _context.childrenon p.Id equals c.ParentId
where d.DeletedDate == null
orderby p.Name ascending, c.Name
select p
Run Code Online (Sandbox Code Playgroud)
然后我得到了Parent对象,但是每个Parent对于孩子都有NULL
如果我试试
from p in _context.Parents.Include("children")
orderby p.Name ascending
select p
Run Code Online (Sandbox Code Playgroud)
查询将返回所有父项和子项,但不会对其进行过滤或排序.
我想要的结果是IEnumerable<Parent>
ie
Parent[0].name = "foo"
Parent[0].children = IEnumerable<Child>
Parent[1].name = "bar"
Parent[1].children = IEnumerable<Child>
Run Code Online (Sandbox Code Playgroud)
Yak*_*ych 10
没有直接的方法可以执行此操作,但您可以使用某种解决方法 - 将父项和子项投影到一个匿名对象上,然后从该对象中选择并返回父项.
请参阅类似的问题:Linq To Entities - 如何过滤子实体
在您的情况下,您将拥有以下内容:
var resultObjectList = _context.
Parents.
Where(p => p.DeletedDate == null).
OrderBy(p => p.Name).
Select(p => new
{
ParentItem = p,
ChildItems = p.Children.OrderBy(c => c.Name)
}).ToList();
List<Parent> resultingCollection = resultObjectList.Select(o => o.ParentItem).ToList();
Run Code Online (Sandbox Code Playgroud)