【问题标题】:How to loop through a child list of objects in Entity Framework 4.1 code first如何首先在 Entity Framework 4.1 代码中循环遍历对象的子列表
【发布时间】: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 &gt; 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 与此命令关联,必须先关闭。

【问题讨论】:

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


【解决方案1】:

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

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

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

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

【讨论】:

  • @Brendan 它在System.Data.Entity 命名空间中。您必须添加对EntityFramework.dll 的引用。但如果你使用ObjectContext API,你可以使用Include("ChildCategories")
【解决方案2】:

添加

MultipleActiveResultSets=True

在连接字符串中

【讨论】:

    【解决方案3】:

    如果您只是希望组合为Parent-&gt;Child (Category Name),为什么不通过属性返回它,而无需进行繁重的工作

    Category 类创建一个partial 类,然后编写以下property

    public string MeAndMyParentCategory
    {
       get
       {
          //I assuming that your 
          // (Child's relation with the parent category called [Parent])
          if(this.Parent != null)
             return string.Format("{0} > {1}", Parent.Name, this.Name);
          return string.Empty
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-08-26
      • 2011-08-11
      • 1970-01-01
      • 1970-01-01
      • 2013-09-14
      • 1970-01-01
      • 1970-01-01
      • 2010-10-22
      • 2013-05-29
      相关资源
      最近更新 更多