比较Linq中的日期逻辑 [英] Comparing the dates logic in Linq

查看:208
本文介绍了比较Linq中的日期逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要查询的结果。

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



但是,正如所要求的结果不来,因为m.PlanDate在查询也比较的时间。
以便在上面的函数参数CreatedDate总是会得到00:00 AM附加到它假设2014年2月17日00:00 AM
,因为它是一个日期选择器控制,我转换入的日期时间,但与我有创建日期的值进行比较是有原来的时机,假设2014年2月17日上午11时58分35秒

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.

我已经搜查了上述问题,并它具有使用AddDays像::
许多解决方案(1)但我不知道它的工作。
还我试着::
http://www.codeproject.com/Articles/499987/LINQ-query-to-compare-only-date-part-of-DateTime

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.

推荐答案

如果您正在使用LINQ to SQL(如你在问题标签中指定),然后简单地获得日期时间的日期部分:

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

通过实体框架,你应该使用 EntityFunctions.TruncateTime(m.PlanDate)

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

这篇关于比较Linq中的日期逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆