【发布时间】:2011-10-05 05:45:32
【问题描述】:
我正在使用Entity Framework 4.1 code first。
这是我的Category 课程:
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
public int? ParentCategoryId { get; set; }
public virtual Category ParentCategory { get; set; }
public virtual ICollection<Category> ChildCategories { get; set; }
}
上面的类是一个自引用的类,例如一个父类可以有一个子类的列表。
我想创建一个父类别名称和子类别名称的字符串值,例如Parent Category 1 > Child Category 1-1。
所以我得到了所有父类别的列表,遍历每个父类别。对于每个父类别,我想遍历子类别列表并将每个子类别的名称与父类别的名称结合起来,这样我就有了类似的东西:
Animal > Lion
Anumal > Baboon
Anumal > Zebra
etc etc etc...
这是我的循环代码。如果有人可以帮助我减少代码行数,我将不胜感激:)
public IEnumerable<Category> GetParentChildCategories()
{
IEnumerable<Category> parentCategoryList = GetParentCategories()
.Where(x => x.IsActive);
List<Category> parentChildCategoryList = new List<Category>();
foreach (Category parentCategory in parentCategoryList)
{
foreach (Category childCategory in parentCategory.ChildCategories)
{
if (childCategory.IsActive)
{
Category category = new Category
{
Id = childCategory.Id,
Name = parentCategory.Name + " > " + childCategory.Name
};
parentChildCategoryList.Add(category);
}
}
}
return parentChildCategoryList;
}
当想要遍历子类别时,它会在第二个 foreach 中爆炸。这是为什么?这是错误:
已经有一个打开的 DataReader 与此命令关联,必须先关闭。
【问题讨论】:
-
这里解释了它抛出异常的原因:stackoverflow.com/questions/4867602/…
标签: c# linq asp.net-mvc-3 entity-framework entity-framework-4.1