简体   繁体   English

为什么当我不使用清单时datetime.now不起作用?

[英]why datetime.now not work when I didn't use tolist?

When I use 当我使用

datacontext.News
    .Where(p => p.status == true)
    .Where(p => p.date <= DateTime.Now)
    .ToList();

the system will return no results; 系统将不返回任何结果;

When I use 当我使用

datacontext.News
    .Where(p => p.status == true)
    .ToList()
    .Where(p => p.date <= DateTime.Now)
    .ToList();

system will return expected results. 系统将返回预期结果。 Can anyone tell me what's up? 谁能告诉我怎么回事?

Thanks in advance ! 提前致谢 !

I best guess is that the time settings on your database server differ from that on your developer machine (or the machine you run .NET on). 我最大的猜测是数据库服务器上的时间设置与开发人员计算机(或运行.NET的计算机)上的时间设置不同。

The difference between the two snippets is that in the second snippet the condition p.date <= DateTime.Now is executed locally, and not on the database server. 这两个代码段之间的区别在于,在第二个代码段中,条件p.date <= DateTime.Now在本地执行,而不是在数据库服务器上执行。

If you want to use local time, you can do this: 如果要使用当地时间,可以执行以下操作:

var now = DateTime.Now;
var newNews = datacontext.News
    .Where(p => p.status == true)
    .Where(p => p.date <= now)
    .ToList();

Why use multiple .Where() ? 为什么要使用多个.Where()

datacontext.News
    .Where(p => p.status && p.date <= DateTime.Now)
    .ToList();

would also work. 也可以。

This answer may also help you understand why it doesn't work as expected: Can multiple compiled linq queries be chained together? 这个答案还可以帮助您理解为什么它不能按预期工作: 可以将多个已编译的linq查询链接在一起吗?

I think that you need to ask it this way... 我认为您需要这样询问...

datacontext.News
    .Where(p => p.status == true && p.date <= DateTime.Now)
    .ToList();

or 要么

datacontext.News
    .Where(p => p.status && p.date <= DateTime.Now)
    .ToList();

the " == true" is only help to understand a little better what on the question. “ == true”仅有助于更好地理解问题。

Its the difference between .NET evaluating date comparisons and SQL; .NET评估日期比较和SQL之间的区别; ToList() executes the response and so I think the second where is using LINQ to Objects. ToList()执行响应,因此我认为第二个地方使用LINQ to Objects。 For date comparisons, you can also consider SqlMethods 对于日期比较,您还可以考虑SqlMethods

http://msdn.microsoft.com/en-us/library/system.data.linq.sqlclient.sqlmethods_members.aspx http://msdn.microsoft.com/zh-CN/library/system.data.linq.sqlclient.sqlmethods_members.aspx

And so you can use: 因此,您可以使用:

SqlMethods.DateDiffDay(d1, d2) > 0

If dates aren't still working for you. 如果日期仍然不适合您。

HTH. HTH。

Check out result in the debugger to see differences between the database server's time and the local time. 在调试器中签出结果,以查看数据库服务器时间与本地时间之间的时差。

var result = datacontext.News
  .Take(1)
  .Select(n => DateTime.Now)
  .ToList()
  .Select(x => new {SqlTime = x, LocalTime = DateTime.Now})
  .Single();

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

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