I recently stumpled upon the problem to dynamically create Linq expressions during runtime. Most examples I found deal with the rather simple task of just comparing one property of a given database entity with a single parameter. Like so:
Session.Query.Where(m => m.Name.Contains("test"))
Which could also be achieved with a far more generic approach like this:
var item = Expression.Parameter(typeof (MyClass), "item");
var property = Expression.Property(item, "Name");
var containsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var searchExpression = Expression.Constant(searchString, typeof(string));
var containsMethodExpression = Expression.Call(property, containsMethod, searchExpression);
var lambda = Expression.Lambda<Func<MyClass, bool>>(containsMethodExpression, item);
query = query.Where(lambda);
However, sometimes the task is somewhat more complex and one wants to attain something like the following:
Session.Query.Where(m => m.SpecialProperty.Any(f => f.Name.Contains("test")));
Where "SpecialProperty" is of the type List<> and the property "Name" is of the type string.
Is it possible to build a Linq expression like this dynamically and how could this be achieved? Are there any performance concerns regarding this approach?