Dynamic Linq Query not working with DateTime field

asp.net-mvc c# datetime dynamic-linq

Question

I am using Dynamic linq to provide my MVC app with data and I have trouble with DateTime fields.

The objects I'm parsing through has a System.Datetime field and I want to check if the dates correspond.

So I try to build the string like this (I'm parsing through a dynamic dictionary to get the data):

string dateToParse = keyValuePair.Value;

DateTime objDate = DateTime.Parse(dateToParse);

valuesToUse.Add("OBJ_DATE.Date == " + objDate.ToShortDateString());

And when I load the data, I do it like this:

var objQry = from pl in m_Db.OBJS.Where(whereConditions)
                               select pl;

The whereConditions variable is a string I build when I have all the data.

But when the data hits the datetime field, the app crashes with the following statement:

Operator '==' incompatible with operand types 'DateTime' and 'Int32'

How can I check a DateTime field using dynamic Linq? I have tried many options, like putting the objDate without ToShortDateString, but with the same effect.

EDIT:

"OBJ_DATE.Date == 2012.01.01", for example

1
0
4/25/2013 8:47:34 PM

Popular Answer

Maybe I'm missing something but don't you have to wrap your date in quotes or something to get it to treat it as a date? I'm trying to remember how the Dynamic Linq works but there must be some way of telling the extension methods that your criteria isn't a primitive type?

OBJ_DATE.Date == "2012.01.01"

UPDATE - Ah ha I knew that code looked funny. Try passing it as a parameter to the extension method rather than trying to do it as one inline string. I was able to come up with this, but I couldn't spend any more time on it. So you'll have to do some digging on how to combine multiple expressions so that you can build them up dynamically the way you say you're doing it in your question.

This is a Copy & Paste from LinqPad

public void Main()
{
    var people = new List<Person>()
    {
        new Person(){Name = "Jpe", BirthDate =DateTime.Parse("March 18, 1980")},
        new Person(){Name = "Bob", BirthDate =DateTime.Parse("July 22, 1989")},
        new Person(){Name = "Sarah", BirthDate =DateTime.Parse("Nov 5, 1995")}
    };

    var firstExpression = System.Linq.Dynamic.DynamicExpression.ParseLambda<Person, bool>("BirthDate = @0", DateTime.Parse("July 22, 1989"));
    //var secondExpression = System.Linq.Dynamic.DynamicExpression.ParseLambda<Person, bool>("Name = @0", "Nick");
    //var finalExpression = Expression.And(firstExpression, secondExpression);
    people.AsQueryable().Where(firstExpression).FirstOrDefault().Dump();
}

public class Person
{
    public string Name{get;set;}
    public DateTime BirthDate {get;set;}
}
3
4/25/2013 10:25:45 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow