2

I've been doing research on how to dynamically make queries for linq. I'm creating a UI for a web application which allows them to select properties from a DB and set where clauses to build reports dynamically. All of the questions I've seen on stack or other sites reference using Dynamic Linq and LinqKit to Solve the problem, example Here . However I can't find an solution to express the syntax.

// This attempts to grab out a title whose from the Database whose
// Copyright Date equals 2006
propName = "CopyrightDate";
Model.Titles.Where(t => t.GetType().GetProperty(propName).GetValue(t, null) == "2006");

I want to do something like this but in Linq to Entities. Linq to entities doesn't support reflection like that, I do not want to pull out all of the data and run Linq to Object the DB is too Large. Any Suggestions on how to write this in Dynamic Linq. Bonus points if you can cast the type to the property type so It can be evaultuated with standard operators (== , > , < , etc..).

1
  • You've already linked to questions that show ways of solving this exact problem, and of course there are plenty of others out there that can be found with some basic research.
    – Servy
    Oct 10, 2014 at 17:04

2 Answers 2

3

What the LINQ-to-entities Where extension method wants, is an Expression<Func<T, bool>>. You can create such an expression like this:

// Create lambda expression: t => t.CopyrightDate == "2006"
ParameterExpression parameter = Expression.Parameter(typeof(T), "t");
var lambda = Expression.Lambda<Func<T, bool>>(
     Expression.Equal(
         Expression.Property(parameter, "CopyrightDate"),
         Expression.Constant("2006")
     ),
     parameter
);

where T is the type of your class containing the CopyrightDate property.

var result = context.Titles
    .Where(lambda)
    .ToList();

A somewhat more general solution is:

Expression<Func<T, bool>> Comparison<T>(ExpressionType comparisonType,
                                        string propertyName, object compareTo)
{
    ParameterExpression parameter = Expression.Parameter(typeof(T), "t");
    MemberExpression property = Expression.Property(parameter, propertyName);
    ConstantExpression constant = Expression.Constant(compareTo);
    Expression body = Expression.MakeBinary(comparisonType, property, constant);
    return Expression.Lambda<Func<T, bool>>(body, parameter);
}
2
  • I switched this to a greaterthan but the problem is the operation doesn't work on nullable types 'DateTime testDate = new DateTime(2006); ParameterExpression parameter = Expression.Parameter(typeof(Title), "t"); var lambda = Expression.Lambda<Func<Title, bool>>( Expression.GreaterThan( Expression.Property(parameter, "CopyrightDate"), Expression.Constant(testDate) ), parameter ); '
    – johnny 5
    Oct 10, 2014 at 17:44
  • 1
    Of what type is your table column? You cannot compare column = 2006 if it is a datetime column! You would have to compare (in SQL) YEAR(column) = 2006. Or, if it is a number column column=2006 or if it is a text column column='2006'. I'd suggest you to first create a working non-dynamic query, before trying to create a complicated expression tree. Oct 10, 2014 at 17:58
0

Here is how you can rewrite your query using Dynamic Linq:

var propName = "CopyrightDate";
var propValue = "2006";
Model.Titles.Where(string.Format("{0}=@0", propName), propValue);

string.Format("{0}=@0", propName) produces the query string for the Where clause, which would be "CopyrightDate=@0" in this case. @0 specifies the parameter for the query, which becomes propValue.

6
  • this seems to generate the correct sql, I need to pull out the TitleName from the Select which I can by Model.Titles.Where(string.Format("{0}=@0", propName), propValue).Select("TitleName") but From here I can't do FirstOrDefault() and the >ToList() extension isn't there. Any Idea on how to do this
    – johnny 5
    Oct 10, 2014 at 17:35
  • 1
    @johnny5 Once you do FirstOrDefault you can't do ToList because it's a single item. Select(string) in the source returns an untyped IQueryable (i.e. not IQueryable<T>) so you need to follow it by a cast to the specific type of the field that you are creating, i.e. Select("TitleName").Cast<string>().FirstOrDefault() and so on. Oct 10, 2014 at 17:43
  • I just mean both extensions weren't accessible, I know you can't chain them :). I switched the example to something more simple which just uses an ID. I'm trying the case however I keep getting an exception "System.Linq.Queryable.Cast<TResult>(system.linq.iqueryable) is a 'method', which is not valid in the given context" var id = Model.Titles.Where(string.Format("{0}=@0", propName), propValue).Select("ID").AsQueryable().Cast<int>.FirstOrDefault(); I also tried this code with out the .AsQueryAble() //(sorry Idk how to format these Comments)
    – johnny 5
    Oct 10, 2014 at 17:55
  • 1
    @johnny5 You forgot parentheses after the Cast<int>: it should be Cast<int>(). Oct 10, 2014 at 17:56
  • Thanks, This should most of the problems, I'm going to mark this as solved for now, I'm sure I can figure out a way to use reflection to cast the type automatically. You've saved me your the best!
    – johnny 5
    Oct 10, 2014 at 18:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.