Linq - reuse expression on child property
        Posted  
        
            by user175528
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by user175528
        
        
        
        Published on 2010-03-15T13:17:38Z
        Indexed on 
            2010/03/15
            13:19 UTC
        
        
        Read the original article
        Hit count: 262
        
LINQ
|lambda-expressions
Not sure if what I am trying is possible or not, but I'd like to reuse a linq expression on an objects parent property.
With the given classes:
class Parent {
 int Id { get; set; }
 IList<Child> Children { get; set; }
 string Name { get; set; }
}
class Child{
 int Id { get; set; }
 Parent Dad { get; set; }
 string Name { get; set; }
}
If i then have a helper
Expression<Func<Parent,bool> ParentQuery() { 
  Expression<Func<Parent,bool> q = p => p.Name=="foo";
}
I then want to use this when querying data out for a child, along the lines of:
using(var context=new Entities.Context) {
 var data=context.Child.Where(c => c.Name=="bar" 
 && c.Dad.Where(ParentQuery));
}
I know I can do that on child collections:
using(var context=new Entities.Context) {
 var data=context.Parent.Where(p => p.Name=="foo" 
 && p.Childen.Where(childQuery));
}
but cant see any way to do this on a property that isnt a collection.
This is just a simplified example, actually the ParentQuery will be more complex and I want to avoid having this repeated in multiple places as rather than just having 2 layers I'll have closer to 5 or 6, but all of them will need to reference the parent query to ensure security.
© Stack Overflow or respective owner