简体   繁体   English

来自 SQL Server 的日期和 C# DateTime 的比较

[英]Comparison of Date From SQL Server and C# DateTime

I have a DateTime column in a SQL Server database.我在 SQL Server 数据库中有一个DateTime列。 The data stored as follows:存储的数据如下:

2020-10-04 23:45:00.527

I tried to compare the date as follows with current date (Date in database should be less than current date)我尝试将日期与当前日期进行如下比较(数据库中的日期应小于当前日期)

 DateTime today = DateTime.Now.Date;

 var result = (from c in TableName
               where (c.Email == email) && 
                     c.Password == password && c.Status == 1 && 
                     c.ValidTill.Date <= today
               select c).ToList();

But unfortunately I get this exception但不幸的是我得到了这个例外

'Date' is not supported in LINQ to Entities. LINQ to Entities 不支持“日期”。 Only initializers, entity members, and entity navigation properties are supported仅支持初始值设定项、实体成员和实体导航属性

Even tried the below method, that doesn't seem to work:即使尝试了以下方法,这似乎也不起作用:

DbFunctions.TruncateTime(c.ValidTill)

My comparison would be like this -我的比较是这样的——

2020-10-04 23:45:00 (Datetime in database) <= 2020-10-10 23:00:00 (current date & time)

You don't need .Date你不需要.Date

    c.ValidTill <= today

or comparing only with date或仅与日期比较

    EntityFunctions.TruncateTime(x.ValidTill) <= today.Date

needs to do the work.需要做的工作。

 var today = DateTime.Now;
 var result = (from c in TableName
               where (c.Email == email) && 
                     c.Password == password && c.Status == 1 && 
                     c.ValidTill <= today
               select c).ToList();

hope it will work.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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