Entity framework 如何迭代实体框架树以查找特定项

Entity framework 如何迭代实体框架树以查找特定项,entity-framework,tree,iteration,Entity Framework,Tree,Iteration,我已经使用实体框架加载了我的产品目录 我想迭代所有项目,以找到一个特定的项目 结构是 类别->[子类别->]产品->选项 子类别、产品和选项是其特定类型的实体集合 所有类型都派生自EntityObject 比如说,我正在寻找选项12,但我不知道它在哪个产品中 如何迭代所有对象以找到选项12?到目前为止,我有这个。在我的EntityObject中,我知道它还不是递归的,但一旦我知道哪些属性是集合,它最终将是递归的,我可能会以错误的方式处理它 public T Find<T>(Type

我已经使用实体框架加载了我的产品目录

我想迭代所有项目,以找到一个特定的项目 结构是 类别->[子类别->]产品->选项 子类别、产品和选项是其特定类型的实体集合 所有类型都派生自EntityObject

比如说,我正在寻找选项12,但我不知道它在哪个产品中

如何迭代所有对象以找到选项12?到目前为止,我有这个。在我的EntityObject中,我知道它还不是递归的,但一旦我知道哪些属性是集合,它最终将是递归的,我可能会以错误的方式处理它

public T Find<T>(Type type, int id) where T : EntityObject
        {    
            //get all properties 
            PropertyInfo[] properties = this.GetType().GetProperties();
            // foreach property find the one
            foreach (PropertyInfo oPropertyInfo in properties)
            {
                // check for type
                if (oPropertyInfo.PropertyType == type)
                {
                    PersistentEntity o = oPropertyInfo.GetValue(this, null) as EntityObject;
                    if (o != null && o.Id == id)
                    {
                        return (T)o;
                    }                        
                }
                // if property has childs, is IEnumerable -> recursive
            }


            return (T)new EntityObject();
        }
public T-Find(类型,int-id),其中T:EntityObject
{    
//获取所有属性
PropertyInfo[]properties=this.GetType().GetProperties();
//foreach属性找到一个
foreach(属性中的PropertyInfo oPropertyInfo)
{
//检查类型
if(opPropertyInfo.PropertyType==类型)
{
PersistentEntity o=OpPropertyInfo.GetValue(this,null)作为EntityObject;
如果(o!=null&&o.Id==Id)
{
返回(T)o;
}                        
}
//如果属性有childs,那么IEnumerable->recursive
}
返回(T)新的EntityObject();
}
这个怎么样

var query = 
from c in categories
from sc in c.SubCategories
from from p in sc.Products
from o in p.Options
where o.Id == 2
select c /* or p?? */;

问题是,用户可能会请求一个不同的对象,如类别、子类别或产品,同时使用和id,我希望用户能够选择要查找的项目类型,但需要了解有关关系的一些信息。除非我误解了你的问题,否则你不能完全动态地完成。这是错误的方法,因为它需要将所有表的全部内容加载到内存中。您应该为每个请求的场景构建正确的linq查询,并只返回满足条件的实体。我知道在内存中加载所有结构是错误的方法,但这是我一直坚持的方法。