0

I'm trying to figure out a way to use methods in a SELECT query in EF Core to reduce the amount of code that is rewritten over and over again. Instead a simple method could be used to query that piece of data. The query looks like so...

 var users = await DbContext.Users.Where(user => user.Id == 1)
                                   .Select(user => new UserDTO
                                   {
                                       Id = user.Id,
                                       Name = user.Name,
                                       Unavailable = user.Tasks
                                                       .Any(task => task.HasTasksToday()),
                                   }).ToListAsync();

The HasTasksToday() code looks like so...

    public bool HasTasksToday()
    {
        return Tasks.Any(task => task.StartedAt.Date == DateTime.Now.Date);
    }

The problem is I get a...

...could not be translated. Either rewrite the query in a form that can be translated...

...error.

I know that using IQueryable may work for this but I am unsure how that would even happen in the select statement as I know only how to use IQueryable on the Users entity.

15
  • what is the rdbms used? MySQL, Mssql? It means EF is not capable of translating the query in question into sql query statement. Commented Jun 29, 2021 at 11:54
  • I know that using IQueryable may work for this Not sure what you mean. It clearly doesn't, because the method call can't be translated into SQL. Use the predicate task.StartedAt.Date = DateTime.Now.Date directly in the query. Commented Jun 29, 2021 at 11:54
  • 1
    @GertArnold task.StartedAt.Date = DateTime.Now.Date or task.StartedAt.Date == DateTime.Now.Date ? Commented Jun 29, 2021 at 11:57
  • 1
    @snr Yeah, just copied OP's code. I type too much SQL to notice such errors. Commented Jun 29, 2021 at 12:00
  • 2
    It sounds like you want an extension method on the Tasks property so the method would be defined something like public static bool HasTasksToday(this IEnumerable<TaskType>) and the select becomes Unavailable = user.Tasks.HasTasksToday()). Is this what you were trying to do? Commented Jun 29, 2021 at 12:17

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.