2012-09-16 36 views
2

UPDATE 這是從波紋管我的評論,我已經與@Slauma discused:如何獲得最上面的父母自我參照對象

因爲我需要連接到傳遞根的所有地區 類別。正如你可以看到,如果我通過2和一些位置有類別 44和44是32的孩子是2的孩子我需要得到這個 位置。位置類別是位於地點 和PlaceCategories之間的數據庫中的N:N表。不重要,但可以提供更好的圖片。我在該地圖上有一張地圖和標記,我 。我可以教育單擊(ID:2) 鏈接,我需要得到所有標記,其中位置類別的根源是 「2」(像foursquare.com地圖)

我有一個自我引用表數據庫。 所以我創建了以下對象:

public class PlaceCategory 
    { 
     public int PlaceCategoryId { get; set; } 
     public string Name{ get; set; } 
     public int? ParentId { get; set; } 

     public virtual PlaceCategory Parent { get; set; } 
     public virtual ICollection<PlaceCategory> Children { get; set; } 

     public string Icon { get; set; } 
    } 

由於定位對象可以有多個類別我有LocationCategory對象:

public class LocationCategory 
    { 
     [Key, Column(Order = 1)] 
     public int LocationId { get; set; } 
     [Key, Column(Order = 2)] 
     public int PlaceCategoryId { get; set; } 
     public Guid UserId { get; set; } 
     public DateTime CreatedOnDate { get; set; } 
     public bool IsPrimary { get; set; } 

     public virtual Location Location { get; set; } 
     public virtual PlaceCategory PlaceCategory { get; set; } 
     public virtual User User { get; set; } 
    } 

Location對象有:

public class Location 
{ 
    ... 
    public virtual ICollection<LocationCategory> LocationCategories { get; set; } 
    ... 

在數據庫中自我引用表我有:

root: Education (id:2, parentId:null) 
child1: School(id:32, parentId:2) 
child2: Elementary(id:42,parentId:32), High(id:43,parentId:32), Higher(id:44,parentId:32) etc. 

我必須根據傳遞的根類別獲取位置列表。

var model = locationRepository.GetLocationss().Where(x => x.LocationCategories???); // but it's a list and don't know how to check top most parent here? 

所以,如果我通過「2」,我應該得到它具有類2,32,42,43,44

+0

「*基於傳遞的根類別的位置列表*」:您能更精確地描述您想要查詢的內容嗎?另外我沒有看到任何自我參照。那麼'root','child1','child2'是指什麼表? – Slauma

+0

我更新了我的整個問題。我忘了添加自我引用對象。在問題的最後,我添加了我需要查詢的示例。 – 1110

+0

「Location」和「LocationCategory」實體是否與您的問題相關?根據你最後一句話,你只想加載'PlaceCategory'實體,基本上是從給定根開始的整個'PlaceCategory'圖的平坦列表,不是嗎?但你爲什麼從'locationRepository開始。GetLocationss()'然後呢? – Slauma

回答

3

這不是由實體框架支持的所有項目,除非你加rootCategoryIdPlaceCategory和在檢索位置時過濾該屬性,但一旦擁有更深的嵌套,此方法將失敗,並且您可能需要獲取某個非根(即擁有自己的父級)類別的所有位置。在這種情況下,存儲根目錄將無濟於事。

這個問題的泛化被稱爲分級或遞歸查詢。這是可以遍歷層次結構並獲取所有必需的嵌套記錄的查詢。通過使用Common Table Expression alias CTE(需要SQL Server 2005或更高版本),可以使用SQL來執行此操作。您可以創建這樣的查詢,並通過dbContext.Database.SqlQuery直接執行。

對於使用.NET 4.5和EDMX(數據庫優先)的EF 5.0,您也可以在SQL Server中將查詢實現爲表值函數,將其映射到EDMX中並在Linq查詢中使用。

+0

+1很高興知道它是如何完成的! – Slauma