我有一个类叫做Structure
:有没有一种方法,使用LINQ/EF获取父/子层次结构中最顶级的项目?
public class Structure
{
public int StructureId { get; set; }
public Structure Parent { get; set; }
}
正如你所看到的,Structure
有父Structure
。这个层次结构中可以有无限数量的结构。
有没有什么办法,使用LINQ(与实体框架),在这个层次结构中获得最顶级的结构?
目前,我不得不击中数据库几次,以找到最上面的父母。最顶端的母公司是一个Structure
用空Parent
属性:
Structure structure = structureRepository.Get(id);
while (structure.Parent != null)
{
structure = structureRepository.Get(structure.Parent.StructureId);
}
// When we're here; `structure` is now the top most parent.
那么,有没有任何优雅的方式来做到这一点使用LINQ/Lambda表达式?理想的情况下,开始用下面的代码:
var structureQuery = from item in context.Structures
where item.StructureId == structureId
select item;
我只是希望能够写出像下面这样我只火了一个数据库命中:
structureQuery = Magic(structureQuery);
Structure topMostParent = structureQuery.Single();
我不认为这是可能的,但我很好奇其他人可能想出的解决方案...... – jeroenh 2010-10-06 15:22:39
哪个数据库,MSSQL? – 2010-10-06 15:22:59
@Nick - MS SQL 2005. @jeroenh - 是的,我也不这么认为。我编写了当前完成这项工作的存储过程,并且它自己碰到了数据库几次。 – GenericTypeTea 2010-10-06 15:24:09