views:

66

answers:

5

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 !

+3  A: 

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).

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.

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();
Steven
A: 

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.

Aristos
This looks nicer but chaining where clauses should produce the same result.
Leom Burke
@Leom Its seems that chaining need first to be List again to work. Maybe its an issue for chaining on linq to sql
Aristos
+1  A: 

Why use multiple .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: http://stackoverflow.com/questions/1544006/can-multiple-compiled-linq-queries-be-chained-together/1544288#1544288

Chris
-1 : He's not using compiled queries and there's nothing wrong with chaining Queryable.Where
David B
A: 

Hey,

Its the difference between .NET evaluating date comparisons and SQL; ToList() executes the response and so I think the second where is using LINQ to Objects. For date comparisons, you can also consider SqlMethods

http://msdn.microsoft.com/en-us/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.

Brian
A: 

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