简体   繁体   中英

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.

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)

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

如果使用EntityFramework 6,则在linq查询中比较日期的推荐方法是DbFunctions.TruncateTime(m.PlanDate)和先前版本的EntityFunctions.TruncateTime(m.PlanDate)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM