2012-12-22 49 views
0

我不知道我缺少這一點: 我有我的EDM-這種關係(不能加載圖片還)WPF樹視圖使用LINQ to實體多重關係

Category_1_ _ 許多 RecipeCategory_ 許多 _ _1_Recipe

基本上每個配方都有一個或多個類別,每個類別可以有0個或多個配方

這裏是我的代碼:

private void LoadData() 

    { 
     List<Category> Categories = new List<Category>(); 
     List<Recipe> Recipes = new List<Recipe>(); 
     var ctx = new MaWEntities(); 
     var query = from x in ctx.Categories select x; 

     Categories = query.ToList<Category>(); 
     foreach (Category c in Categories) 
     { 
      TreeViewItem TVP = new TreeViewItem() { Header = c.CategoryName.ToString() }; 

      var qq = from xx in ctx.RecipeCategories.Where(o => o.CategoryId == c.CategoryId) select xx; 
      foreach (var rc in qq) 
      { 

       TreeViewItem TVC = new TreeViewItem() { Header = rc.Recipe.RecipeName.ToString() }; 
       TVP.Items.Add(TVC); 
       //TVP.IsExpanded = true; 
      } 
     } 

    } 

我想完成的是一個treeview,其父節點是categoryname,子節點是recipe名稱。我知道如何使用Linq從基表(配方到RecipeCategory)鑽入關係表中。還必須有一種方法再次遍歷分類表。我還應該提到,即使該類別沒有任何食譜,我仍然希望在樹視圖中將類別名稱看作父級。

回答

1

我發現我在這種情況下的問題不是我的代碼不工作;相反,我忽略了添加樹視圖項目到我的樹視圖。另外,這個添加需要在foreach循環之後完成。 List Categories = new List(); List Recipes = new List(); var ctx = new MaWEntities(); var query = from x in ctx.Categories select x;

 Categories = query.ToList<Category>(); 
     foreach (Category c in Categories) 
     { 
      TreeViewItem TVP = new TreeViewItem() { Header = c.CategoryName.ToString() }; 

      var query2 = from xx in ctx.RecipeCategories.Where(o => o.CategoryId == c.CategoryId) select xx; 
      foreach (var rc in query2) 
      { 

       TreeViewItem TVC = new TreeViewItem() { Header = rc.Recipe.RecipeName.ToString() }; 
       TVP.Items.Add(TVC); 

      } 
      tvwRecipe.Items.Add(TVP); 
     }