-2

I am trying to do a date range filter using the following linq:

IQueryable<Movies> movies= _context.Movies
            .OrderByDescending(i => i.Id).Select(i => i);

DateTime startDate = Convert.ToDateTime(searchStartDate);
DateTime endDate = Convert.ToDateTime(searchEndDate);

movies = movies.Where(i => Convert.ToDateTime(i.TransDate) >= startDate &&
                Convert.ToDateTime(i.TransDate) <= endDate)
                .OrderByDescending(j => j.Id);

But it is't working and is giving me InvalidOperationException: The LINQ expression '...' could not be translated.

NOTE: The database I was given to work with has TransDate column in string format('YYYY-MM-DD'), hence this question.

10
  • 1
    Why would you store a date as a string in a database ?
    – TheGeneral
    Dec 2, 2020 at 4:32
  • 3
    If your date in not a string in the database then just remove Convert.ToDateTime in the query. If it is however, change your database
    – TheGeneral
    Dec 2, 2020 at 4:37
  • 1
    Please show us the CREATE TABLE script for the database table.
    – mjwills
    Dec 2, 2020 at 4:47
  • I wish it was stored as datetime in database too but unfortunately, I wasn't the one to create the database.
    – Aaron
    Dec 2, 2020 at 6:24
  • What is the format it is stored in in the database? Dec 2, 2020 at 7:47

3 Answers 3

3

While storing dates as string in database is not a good idea, at least the chosen format is orderable. And while EF Core does not provide translatable method for converting string to date, it allows you to have entity property of type DateTime (as it should have been), and map it to string column in database using value converter. Thus, you would write query against DateTime, and EF Core will convert the constant/parameter values to string and pass them to the SQL query.

Applying it to your case:

Model:

public class Movie
{
    // other properties...

    public DateTime TransDate { get; set; }
}

Configuration:

const string DateFormat = "yyyy-MM-dd";

modelBuilder.Entity<Movie>().Property(e => e.TransDate)
    .HasConversion(
        dateValue => dateValue.ToString(DateFormat, CultureInfo.InvariantCulture),
        stringValue => DateTime.ParseExact(stringValue, DateFormat, CultureInfo.InvariantCulture)
    )
    .IsRequired()
    .IsUnicode(false) // arbitrary
    .HasMaxLength(10); // arbitrary

LINQ query usage:

IQueryable<Movie> movies = ...;
DateTime startDate = ...;
DateTime endDate = ...;

movies = movies
    .Where(e => e.TransDate >= startDate && e.TransDate <= endDate);
0

Try removing one OrderByDescending you already have ordered it in the first statement. You are ordering the same query twice.

0

To understand the problem, you'll have to be aware of the differences between IEnumerable and IQueryable.

IEnumerable

An object of a class that implements IEnumerable<...> represents a sequence of similar objects. It holds everything to get the first element of the sequence, and as long as you've got an element, you can try to get the next one.

At its lowest level, this is done using GetEnumerator and repeatedly calling MoveNext() / Current, like this:

IEnumerable<Movie> movies = ...
IEnumerator<Movie> enumerator = movies.GetEnumerator();

// try to get the next element:
while (enumerator.MoveNext())
{
    // There is a next element
    Movie movie = enumerator.Current;
    ProcessMovie(movie);
}

Deep inside foreach will do something like this. Every LINQ method that doesn't return IEnumerable<...> will also deep inside call GetEnumerator / MoveNext / Current.

An IEnumerable is meant to be executed by your process, hence the IEnumerable has access to all your procedures.

IQueryable

Although an IQueryable looks like an IEnumerable, it represent the potential to get an enumerable sequence.

For this, the IQueryable has an Expression and a Provider. The Expression holds what data must be fetched in some generic format; the Provider knows where he must fetch the data (Usually a database management system), and what language to use when fetching the data (usually SQL).

As long as you concatenate LINQ methods that return IQueryable<...> the Expression changes. The query is not executed, the database is not contacted. We say that the LINQ method uses deferred execution, or lazy execution. Concatenating such LINQ statements is not expensive.

The LINQ methods that don't return IQueryable<...>, like ToList(), ToDictionary(), FirstOrDefault(), Count(), Any(), are the expensive ones, just like foreach they will deep inside call GetEnumerator().

When you call GetEnumerator(), the Expression is sent to the Provider, who will translate the Expression into SQL and execute the Query. The fetched data is returned as an IEnumerator<...> of which you can call MoveNext() / Current.

Some Providers are smarter than others. For instance, some of them will not fetch the data when you get the Enumerator, but fetch it at the first MoveNext. Others won't fetch all requested data at once, but fetch the data "per page", so if you decide to enumerate only two or three items, then only the first page of Movies are fetched, not all 10000 of them.

But what has this to do with my question?

You use a method that your Provider doesn't know: Convert.ToDateTime. Hence it can't translate it into SQL. In fact, there are several LINQ methods that are not supported by entity framework. See Supported and Unsupported LINQ methods

Your compiler doesn't know how smart the Provider is, so your compiler can't complain. You'll get your error at runtime.

So you can't use Convert.ToDateTime, nor methods like Datetime.Parse.

What to do?

You wrote that the strings that you want to convert are in format 'YYYY-MM-DD'. What you could do, is use string handling routines to separate them into "YYYY", "MM" and "DD". It depends on your provider whether you can use String.SubString.

Then use class DbFunctions to CreateDateTime

.Where(x => ... && DbFunctions.CreateDateTime(
      x.TransDate.SubString(0,4),               // YYYY
      x.TransDate.SubString(5, 2),              // MM
      x.TransDate.SubString(8, 2),              // DD
      0, 0, 0) < endDate;

If your Provider also doesn't accept SubString, search for other methods to extract the YYYY, MM and DD. I know Sqlite has a Date method to convert strings to DateTime.

If you can't find any proper string manipulation routines, consider to convert endDate into format "YYYY-MM-DD" and return compare the TransDate string with the endDateSTring

string endDateString = String.Format("{0:D04}-{1:D02}-{2:D02}", endDate.Year, endDate.Month, ...)

Fiddle a bit with it, until you've got the correct format. Then use:

.Where(x => ... && x.TransDate < endDateString)

If that also does not work, create the SQL query yourself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.