I am using Entity Framework 4.1 code first
.
Here is my Category
class:
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; }
}
The above class is a self-referencing category, for example, a parent category can have a list of child categories.
I want to create a string value of the parent category name and the child category name, for example, Parent Category 1 > Child Category 1-1
.
So I get a list of all the parent categories, loop through each parent category. And for each parent category I want to loop through the child category list and combine each child category's name to the parent category's name, so that I have something like:
Animal > Lion
Anumal > Baboon
Anumal > Zebra
etc etc etc...
Here is my looping code. If anyone can help me reduce the lines of code then I would appreciate it :)
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;
}
It bombs out in the 2nd foreach when wanting to loop through the child categories. Why is is this? Here is the error:
There is already an open DataReader associated with this Command which must be closed first.