How to iterate an Entity Framework tree to find a specific item
I have loaded my product catalog using Entity Framework
I would like to iterate all items to find a specific item the structure is Category -> [Subcategory ->] Product -> options Subcategory, product and options are EntityCollection of their spe开发者_如何学Ccific type All types derive from EntityObject
Let's say I'm looking for option 12 but I don't know in which product it is in.
How can I iterate all objects to find the option 12 ? I have this so far. in my EntityObject, I know it's not recursive yet but will eventually be once i know which properties are collections, I might be approaching it the wrong way ...
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();
}
How about this?
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?? */;
精彩评论