Query only Date in a DateTime field with LINQ

4

I'm generating a report in an app I'm developing, but with a little problem. When I send a query in a date range, I can not get anything because it is a DATETIME (I can not change to date only, because I need the time in some moments). So I'm just trying to send Date, but it returns an error.

  

Message="The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."

var query = from td in this.Table.AsNoTracking()
                    join u in base.context.Users on  td.UserId equals u.Id
                    where (!onlyEnabled) || (u.Enable)
                    select td;
            //AQUI TENTO PASSAR APENAS O DATE
        if (initialOpeningDate.HasValue)
            query = query.Where(td => DbFunctions.TruncateTime(td.OpeningDate.Date) >= initialOpeningDate.Value);
          //AQUI TENTO PASSAR APENAS O DATE
        if (finalOpeningDate.HasValue)
            query = query.Where(td => DbFunctions.TruncateTime(td.OpeningDate.Date) <= finalOpeningDate.Value);

        if (onlyExpired)
            query = query.Where(td => td.ExpireDate < DateTime.Now);

        return query.ToList();
    
asked by anonymous 09.10.2015 / 17:00

1 answer

2

Your approach is correct, using DbFunctions.TruncateTime , but I believe you can not pass the conversion into the Linq statement, solving the variables before, as follows:

    if (initialOpeningDate.HasValue) 
    {
        var queryInitialOpeningDate = initialOpeningDate.Value.Date;
        query = query.Where(td => DbFunctions.TruncateTime(td.OpeningDate.Date) >= queryInitialOpeningDate);
      //AQUI TENTO PASSAR APENAS O DATE
    }
    if (finalOpeningDate.HasValue) 
    {
        var queryFinalOpeningDate = finalOpeningDate.Value.Date;
        query = query.Where(td => DbFunctions.TruncateTime(td.OpeningDate.Date) <= queryFinalOpeningDate);
    }
    
09.10.2015 / 17:05