Home > Back-end >  How to use DayOfWeek on a datetime in a LINQ Query on .Net CORE
How to use DayOfWeek on a datetime in a LINQ Query on .Net CORE

Time:11-23

I try to use DayOfWeek in a LINQ query but it doesn't work. I am using framework .Net Core 6

I have tried:

var test =  await _context.DailyConsumption.Where(t => t.Time.DayOfWeek == DayOfWeek.Sunday).ToListAsync();

--

var test =  await _context.DailyConsumption.Where(t => EntityFunctions.TruncateTime(t.Time).Value.DayOfWeek == DayOfWeek.Sunday).ToListAsync();

and

DateTime firstDate = new DateTime(1753, 1, 7);
var test =  _context.DailyConsumption.Where(t => EntityFunctions.DiffDays(firstDate, t.Time) % 7 == 1).ToListAsync();

The 3 lines of code above gives me the same result:

InvalidOperationException: The LINQ expression 'DbSet<DailyConsumption>().Where(d => (int)d.Time.DayOfWeek == 0)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'

My program can't even translate the code into an SLQ request, I don't understand why.

According to some sources on the internet, DayOfWeek must be used differently in .NET Core framework. I'm stuck, there are not many people with this problem ...

EDIT : If it can help, Here is my model :

 [Keyless]
public partial class DailyConsumption
{
    public string Prm { get; set; } = null!;
    public DateTime Time { get; set; }
    public float Power { get; set; }
    public float PowerConsumption { get; set; }
}

CodePudding user response:

The reason is that implicit client evaluation has been disabled from EF Core 3.

You can switch to client evaluation explicitly by inserting a call to AsEnumerable like below:

var test =  _context.DailyConsumption.AsEnumerable()
    .Where(t => t.Time.DayOfWeek == DayOfWeek.Sunday).ToList();
  • Related