C#| .NET 4.5 |實體框架5獲取所有孩子到一個列表 - 遞歸C#
我在實體框架類,看起來像這樣:
public class Location
{
public long ID {get;set;}
public long ParentID {get;set;}
public List<Location> Children {get;set;}
}
ID是位置的標識,PARENTID它鏈接到父,和兒童包含了所有的孩子位置父母的位置。我正在尋找一些簡單的方法,可能會遞歸地將所有「位置」和他們的孩子都放到一個包含Location.ID的列表中。我無法遞歸地概念化這個問題。任何幫助表示讚賞。
這是我到目前爲止,它的擴展實體類,但我相信這是可以做到更好/更簡單:
public List<Location> GetAllDescendants()
{
List<Location> returnList = new List<Location>();
List<Location> result = new List<Location>();
result.AddRange(GetAllDescendants(this, returnList));
return result;
}
public List<Location> GetAllDescendants(Location oID, ICollection<Location> list)
{
list.Add(oID);
foreach (Location o in oID.Children)
{
if (o.ID != oID.ID)
GetAllDescendants(o, list);
}
return list.ToList();
}
修訂
我最後寫的在SQL中遞歸,將其放入SP中,然後將其拖入實體中。看起來更乾淨,對我來說比使用Linq容易一些,並且Linq和Entity評論似乎並不是最佳路線。感謝所有的幫助!
實體框架不包含任何與遞歸查詢有關的事情。 – Aron
是的,我希望擴展此功能,請參閱我的編輯。 – Will
我以爲你想要一個實體框架解決方案,而不是由實體框架支持的Linq To Object解決方案延遲加載......我研究了實體框架6源代碼並希望實際添加功能......但是Microsoft將relavent類設置爲「internal」。 BAS $%^ DS – Aron