我不知道我缺少什么:我在EDM中有这种关系 - (还不能加载图片)
category_1_ _ 许多 cepporecategory_ 许多 _ _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,其父节点是类别名称,而子节点是食谱名称。我知道如何使用LINQ从基础表(食谱到配方)钻入关系表。还必须有一种方法可以再次穿越类别表。我还应该提到,即使该类别没有任何食谱,我仍然希望将类别名称视为TreeView中的父母。
我发现在这种情况下我的问题不是我的代码不起作用。相反,我忽略了将树视图项目添加到我的树视图中。另外,此添加需要在foreach循环之后完成。列表类别=新列表(); 列表食谱=新列表(); var ctx = new mawentities(); var query =从ctx中的x中。类别选择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);
}