c# Linq method is not following one of my conditions that I set

Viewed 76

I'm trying to create a list like you see below.

For some reason, it follows the first two conditions, isPublished and IsRPG == false. But it ignores the ShelfDate.

I want all games where the ShelfDate is greater than or equal to the current date.

But it will show games that have any ShelfDate...

BTW ShelfDate is of type DateTime.

Here is my code:

var games = await _context.Game
   .Where(x => x.IsPublished == isPublished && x.IsRPG == false && x.ShelfDate >= DateTime.Now)
   .Select(x => new GameEntity
   { ... }

Here are the models for Game and GameEntity:

public partial class Game
{
    public long Id { get; set; }
    public string Title { get; set; }
    public DateTime ShelfDate { get; set; }
    public DateTime IsPublished { get; set; }
    public bool IsRPG { get; set; }
    public string Description { get; set; }
}   


public partial class GameEntity
{
    public string Title { get; set; }
    public DateTime ShelfDate { get; set; }
    public DateTime IsPublished { get; set; }
    public bool IsRPG { get; set; }
}      

Am I doing anything wrong?

I am getting no errors.

Thanks!

2 Answers

Putting the response here.

DateTime.Now is not recognized by your data provider, and needs to be set earlier and not be evaluated by the query, assuming you're using Entity Framework.

You are using the wrong syntax here. You are using the lambda operator =>. You have to use the comparison here. Either >= or <=

It should be like this.

var games = await _context.Game
   .Where(x => x.IsPublished == isPublished && x.IsRPG == false && x.ShelfDate <= DateTime.Now)
   .Select(x => new GameEntity
   { ... }
Related