0

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; }
}
sylvaing
  • 7
  • 6
  • What type is `t.Time`? Is it a `DateTime`? – nbokmans Nov 21 '22 at 12:34
  • Yes it is a dateTime, I just added the model I use to my question – sylvaing Nov 21 '22 at 12:36
  • see https://stackoverflow.com/questions/68737681/the-linq-expression-could-not-be-translated-either-rewrite-the-query-in-a-form, looks like the issue is that you can't use `Where` in its normal form with Entity Framework. – frankM_DN Nov 21 '22 at 12:45
  • Does this answer help? https://stackoverflow.com/questions/40271588/entity-framework-dayofweek – Scott Hannen Nov 21 '22 at 20:08
  • @ScottHannen No, this answer does not help me because the person does not use net core. – sylvaing Nov 22 '22 at 07:52
  • @frankM_DN This answer doesn't help me anymore, I tried to generate my clause where as they do but it's not working – sylvaing Nov 22 '22 at 07:53

1 Answers1

0

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();
Rena
  • 30,832
  • 6
  • 37
  • 72
  • Just note that this will be executed in memory and not in the DB. So all `DailyConsumption` will be loaded by EF before applying the `Where` clause and materializing the enumeration with `ToList()` – Philippe Nov 22 '22 at 09:24