c# - 如何首先循环遍历 Entity Framework 4.1 代码中的子对象列表

标签 c# linq asp.net-mvc-3 entity-framework entity-framework-4.1

我正在使用 Entity Framework 4.1 代码优先

这是我的 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,必须先将其关闭。

最佳答案

EF 在您迭代 parentCategoryList 时打开一个阅读器。然后,当您尝试迭代 parentCategory.ChildCategories 时,EF 将再次打开一个阅读器。由于有打开的阅读器,它会抛出错误。

您应该做的是预先加载 ChildCategories。这样 EF 就不必再次打开阅读器。

因此在您的 GetParentCategories() 方法中,使用 Include 预先加载它们

return db.Categories.Include(c => c.ChildCategories).Where(/* */);

关于c# - 如何首先循环遍历 Entity Framework 4.1 代码中的子对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7657160/

相关文章:

c# - asp.net mvc 从 FormCollection 填充 viewModel

C# 如何向具有多个对象类的 LDAP 添加条目

c# - 在 XML 中选择特定节点列表

c# - 如何将 Entity Framework 中的数据绑定(bind)到数据网格?

asp.net-mvc - MVC 动态值的不引人注目的范围验证

C# UWP : copy file to folder inside local folder not functioning properly

C# Gridview - 在添加新列失败时检查列是否已存在

c# - 添加列表到列表

jquery - 如何向 jQuery Mobile 添加页面特定逻辑?

visual-studio-2010 - 命名空间 'Model'的类型在命名空间中不存在