Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing the dates logic in Linq

I want to query the result

public resultType GetData(int ClientID, DateTime CreatedDate)
{
    var Row = DB.tblPlans
                .Where(m => m.fkClient_Id == ClientID && m.PlanDate <= CreatedDate)
                .OrderByDescending(m => m.Id)
                .FirstOrDefault();
}

But the results are not coming as required because the "m.PlanDate" in the query is comparing the time also. so The parameter "CreatedDate" in the above function will always get "12:00:00 AM" attached to it suppose "2/17/2014 12:00:00 AM" because it is a datepicker control and I am converting it into datetime but the value of created date with which I have to compare it is having original timing suppose "2/17/2014 11:58:35 AM"

and that is why I am not getting the desired result.

I think the result will be fine if time portions get removed.

I have searched the above problem and it have many solutions like:: using AddDays(1); but I am not sure about it's working. also I tried:: http://www.codeproject.com/Articles/499987/LINQ-query-to-compare-only-date-part-of-DateTime

Please suggest me a better way to do this as this is not the first time I am getting this problem.

like image 624
Sweetie Avatar asked Jan 12 '23 04:01

Sweetie


2 Answers

If you are using Linq to SQL (as you specified in question tag), then simply get Date part of DateTime:

var Row = DB.tblPlans
            .Where(m => m.fkClient_Id == ClientID && m.PlanDate.Date <= CreatedDate)
            .OrderByDescending(m => m.Id)
            .FirstOrDefault();

With Entity Framework you should use EntityFunctions.TruncateTime(m.PlanDate)

like image 150
Sergey Berezovskiy Avatar answered Jan 16 '23 18:01

Sergey Berezovskiy


Have you tried this:

public resultType GetData(int ClientID, DateTime CreatedDate)
{
    var Row = DB.tblPlans
                .Where(m => m.fkClient_Id == ClientID && m.PlanDate.Date <= CreatedDate)
                .OrderByDescending(m => m.Id)
                .FirstOrDefault();
}
like image 34
Usman Khalid Avatar answered Jan 16 '23 17:01

Usman Khalid