Home > Enterprise >  How to know if a DateTime is Between two Dates in Entity Framework core
How to know if a DateTime is Between two Dates in Entity Framework core

Time:02-03

I have an application and a DB created by Entity Framework Core, I have and entity called ListUsers with this property: public DateTime CreationDate { get; set; }

I have another class with properties to do a filter, this is my filter class:

 public string Neighborhood { get; set; }
 public DateTime? InitDate { get; set; }
 public DateTime? EndDate { get; set; }

I have another properties to do the filter, with other properties works fine but when I send the DateTime properties it does not work, this is my Linq query to do the filter:

var result = await _context.ListUsers.Include(lu => lu.List).ThenInclude(u => u.User)
                .Where(
                   lu => lu.CreationDate.Date >= filter.InitDate
                && lu.CreationDate.Date <= filter.EndDate
                && lu.Country == filter.Country
                && lu.City == filter.City
                && lu.Locality == filter.Locality
                && lu.Neighborhood == filter.Neighborhood
                && lu.List.Id == filter.ListId
            ).ToListAsync();
            return result;

in my DB there are two registers with this date: "2021-08-01 17:47:12.8614628" but "result" always is empty, I'm sending from postman this json:

{ "listId": "090A5C4D-04AB-434E-A0EF-C579B6D1D0C8",
"initDate": "2021-08-01", "endDate": "2021-08-12", "neighborhood": "portsland" }

Any possible solution?

CodePudding user response:

You filter on Country, City and Locality, but the JSON does not contain any of them, so the filtering happens on null values, which is most likely the reason why you get no results.

You need to either provide all values in the JSON, or change the filtering to do nothing for null values.

Example filter:

&& (filter.Country == null || lu.Country == filter.Country)
  •  Tags:  
  • Related