Linq Queries : Translate Local variable references RRS feed

  • Question

  • Hello !

    I'm using the information from this MSDN Blog :


    everything works very well except the case when I have a DateTime variable inside the query that I have to translate .

    This is my case :

    On my database I have the table orders where dt column have Date Type and store only the date.

    Now if I have this query :

       DateTime dt1 = Convert.ToDateTime("01/01/2012");
        var query = db.Orders.Where(c => c.dt == dt1);

    If I try to translate , the returned expression is :

    SELECT * FROM (SELECT * FROM Orders) AS T WHERE (dt = '01/01/2012 12:00:00 AM')

    As you can see the translated query contains the time at the end , and my query everytime return no records.

    What can I do that in translated query the value to be only the date without the time.?

    I try many variants , I format the variable only to date format , but it's the same thing.

    Thank you !

    • Edited by dcode25 Friday, February 20, 2015 12:23 AM
    Thursday, February 19, 2015 10:16 PM


  • the simpliest solution would be to use the Date-Portion of your DateTime-Object

    another Solution would be the ToString method like

    c.dt.ToString("MM.dd.YYYY") == dt1.ToString("MM.dd.YYYY")

    it may not be exactly like this... but you'll find the right toString method yourself. There is even a toString-Method wich you can pass a CultureInfo-object, but i found the best way for coparing Dates is to provide a const format-string that is used to compare DateTime-Types.

    To put in some extra suggar, you could try to override the DateTime-Equal-Operator-Implementation.

    • Marked as answer by Fred Bao Tuesday, March 3, 2015 11:09 AM
    Friday, February 20, 2015 8:48 AM