Comparing Date Logic in Linq

I want to request a 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 do not come as needed, since "m.PlanDate" in the query also compares the time. therefore the parameter "CreatedDate" in the above function will always be attached to it "12:00:00 AM", presumably "2/17/2014 12:00:00 AM" because it is a datepicker control, and I will convert it to datetime. but the value of the created date, with which I must compare, has the original time. "2/17/2014 11:58:35 AM"

and that’s why I don’t get the desired result.

I think the result will be perfect if parts of the time are removed.

I was looking for the above problem and it has many solutions, such as :: using AddDays (1); but I'm not so sure about that. also i tried: http://www.codeproject.com/Articles/499987/LINQ-query-to-compare-only-date-part-of-DateTime

Please suggest me the best way to do this, as this is not the first time I get this problem.

+4
source share
3 answers

If you use Linq to SQL (as indicated in the question tag), just get a Date DateTime:

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

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

+7
source

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();
}
+1
source

linq-, EntityFramework 6, DbFunctions.TruncateTime(m.PlanDate) EntityFunctions.TruncateTime(m.PlanDate)

+1

Source: https://habr.com/ru/post/1527277/


All Articles