如何使用C#和实体框架避免递归对象获取

如何使用C#和实体框架避免递归对象获取,c#,entity-framework-4,C#,Entity Framework 4,现在,为了访问自连接对象的所有子类别,我正在进行如下查询 var productCategories = db.Categories.Inlcude("ChildCategories") .Inlcude("ChildCategories.ChildCategories") .Inlcude("ChildCategories.ChildCategories.ChildCategories") .Inlcude("ChildC

现在,为了访问自连接对象的所有子类别,我正在进行如下查询

var productCategories = db.Categories.Inlcude("ChildCategories")
            .Inlcude("ChildCategories.ChildCategories")
            .Inlcude("ChildCategories.ChildCategories.ChildCategories")
            .Inlcude("ChildCategories.ChildCategories.ChildCategories.ChildCategories")
            .Inlcude("ChildCategories.ChildCategories.ChildCategories.ChildCategories.ChildCategories")
            .Inlcude("ChildCategories.ChildCategories.ChildCategories.ChildCategories.ChildCategories.ChildCategories")

对于这种查询,可以做些什么?

要允许IQueryable获取所有内容(与延迟加载相反),可以禁用DBContext上的延迟加载

 using(DBContext db = new DBContext) {
      db.ContextOptions.LaxyLoadingEnabled = false;
      // TODO: Other code here
 }
编辑:修复了对@Slauma评论的回复

如果ChildCategory是Category(继承)的子类:

如果希望iQuery能够获取
ChildCategory
的所有内容,可以使用
OfType()
方法

 var productCategories = db.Categories.OfType<ChildCategories>();
var productCategories=db.Categories.OfType();

要允许iQueryEnable获取所有内容(与延迟加载相反),可以禁用DBContext上的延迟加载

 using(DBContext db = new DBContext) {
      db.ContextOptions.LaxyLoadingEnabled = false;
      // TODO: Other code here
 }
编辑:修复了对@Slauma评论的回复

如果ChildCategory是Category(继承)的子类:

如果希望iQuery能够获取
ChildCategory
的所有内容,可以使用
OfType()
方法

 var productCategories = db.Categories.OfType<ChildCategories>();
var productCategories=db.Categories.OfType();

可能一个db.Categories.ToList()就可以了,因为它将获取所有类别。但是我必须承认,如果你需要where(),我不知道该怎么做,很可能db.Categories.ToList()就可以了,因为它将获取所有类别。但我必须承认,我不知道怎么做,如果你需要一个where()…为什么
的类型
?它用于过滤派生实体,但是
ChildCategories
是与
Category
类型相同的导航集合,这里没有派生任何内容。@Slauma是的,我的错误,当我看到Child这个词时,我认为是继承。为什么
的类型是
?它用于过滤派生实体,但是
ChildCategories
是与
Category
类型相同的导航集合,这里没有派生任何内容。@Slauma是的,我的错误,当我看到Child这个词时,我认为是继承。