2012-12-31 47 views
1

它加載類別但始終爲空父代。我想獲得給定ID的層次結構類別。父類別在實體框架延遲加載模式下始終爲空

public static Category GetCategory(System.Guid ID, ActionLinkInfo AInfo) 
     { 
      Category category = null; 

      using (TIKSN.STOZE.Data.StozeContext DContext = new Data.StozeContext()) 
      { 
       var cats = from cat in DContext.Categories where cat.ID == ID select cat; 

       foreach (Data.Category Cat in cats) 
       { 
        category = new Category(Cat, Cat.Parent == null ? null : GetCategory(Cat.Parent.ID, AInfo), AInfo); 
       } 
      } 

      return category; 
     } 

回答

1

試試這個:

var cats = from cat in DContext.Categories.Include("Parent") where cat.ID == ID select cat; 

或者你可以改變你的模式,包括ParentIDCategory類整數:

public class Category { 

    /* (...) */ 

    public int ParentID { get; set; } 

    [ForeignKey("ParentID")] 
    public Category Parent { get; set; } 
} 

這樣,您就可以從數據庫中獲取Cat.ParentID沒有加載整個Parent對象。

+0

但這不是懶加載。這是急切的負載。 – TIKSN

0

該解決方案明確要求加載父項。

public static Data.Entity.Category GetCategory(long ID) 
    { 
     Data.Entity.Category category; 

     using (Data.StozeContext DContext = new Data.StozeContext()) 
     { 
      var categories = from SingleCategory in DContext.Categories.Include("Parent") where SingleCategory.ID == ID select SingleCategory; 

      category = categories.Single(); 
     } 

     return category; 
    } 
相關問題