See Date only, in a Datetime field with LINQ

Asked

Viewed 1,604 times

4

I’m generating a report in an app that I’m developing, but I have a little problem. When sending a query in a date interval, I can’t get anything, because it is a DATETIME (I can’t change to date only, because I need the time in a few moments). So I’m trying to send only 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();

1 answer

2


Your approach is correct, using DbFunctions.TruncateTime, but I believe you may not pass the conversion into the Linq sentence, 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);
    }
  • 2

    Really, missed it. But keeps repeating the same mistake.

  • I forgot to mention, I’m using the EF.

  • @Viniciusmatos Adjusted the answer. See now.

  • I managed to fix it. The problem was . Date at the end. It was "breaking" my query. But, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.