0

How would you translate the following generic Lambda function into a lambda expression :

context.AssociateWith<Product>(p => p.Regions.Where(r => r.Country == 'Canada')

I'm trying to create a full lambda expression without any <T> or direct call. Something like :

void AddFilter(ITable table, MetaDataMember relation)
{
    var tableParam = Expression.Parameter(table.ElementType, "e");
    var prop = Expression.Property(tableParam, relation.Name);
    var func = typeof(Func<,>).MakeGenericType(table.ElementType, relation.type)
    var exp = Expression.Lambda(func, prop, tableParam);
}

This will produce e.Regions... but I'm unable to get the Where part from there...

Mathlec
  • 318
  • 1
  • 6

2 Answers2

2

I know I'm very late in the game with my answer and likely this is not the exact solution you are looking for (still uses the frequently), but maybe it will help you and others building their expression:

/* 
example: Session.Query.Where(m => m.Regions.Where(f => f.Name.Equals("test")))
*/ 

var innerItem = Expression.Parameter(typeof(MyInnerClass), "f");
var innerProperty = Expression.Property(innerItem, "Name");
var innerMethod = typeof(string).GetMethod("Equals", new[] { typeof(string) });
var innerSearchExpression = Expression.Constant(searchString, typeof(string));
var innerMethodExpression = Expression.Call(innerProperty, innerMethod, new[] { innerSearchExpression });
var innerLambda = Expression.Lambda<Func<MyInnerClass, bool>>(innerMethodExpression, innerItem);

var outerItem = Expression.Parameter(typeof(MyOuterClass), "m");
var outerProperty = Expression.Property(outerItem, info.Name);
/* calling a method extension defined in Enumerable */
var outerMethodExpression = Expression.Call(typeof(Enumerable), "Where", new[] { typeof(MyInnerClass) }, outerProperty, innerLambda);
var outerLambda = Expression.Lambda<Func<MyOuterClass, bool>>(outerMethodExpression, outerItem);
query = query.Where(outerLambda);

Based on an answer posted here: Creating a Linq expression dynamically containing a subquery.

Community
  • 1
  • 1
UnclePaul
  • 515
  • 5
  • 17
0

Try this, it's not pretty but it gives you a valid expression for the whole structure. You could define the inner lambda as an expression but you would still have to compile it before you could pass it to Where(), so for the purposes of this answer it seems redundant.

Expression<Func<Product, IEnumerable<Region>>> getRegions = 
      p => p.Regions.Where(r => r.Country == "Canada");
Sam
  • 6,167
  • 30
  • 39
  • I'm more looking into something that would use non typed parameters. I'll precise my question more. Thanx tho! – Mathlec Sep 29 '09 at 00:32