2

My business logic is following. I have CustomerEvents table. The table contains CreatedAt column and CustomerId column. I need to retrieve last and previous event for particular customer. About the last I have not problems. But what to do with the previous? I have tried ElementAtOrDefault. But it does not work. I will show you my code:

PrevReDepDate = context.CustomerEvents.Where(y
        => y.Customer.CustomerId == 123 && y.EventType == "deposit" && y.Again == true)
    .Select(y => y.CreatedAt).OrderByDescending(y => y)
    .ElementAtOrDefault(1),

It does not work. It seems to me, it's happening because EF is not able to execute it on the database server side. Here is exception text:

System.InvalidOperationException: Processing of the LINQ expression 'DbSet .ElementAtOrDefault(__p_0)' by 'NavigationExpandingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core. See https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed information. at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)

Am I right? If yes, any alternatives for getting previous element like with the help of ElementAtOrDefault?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Aleksej_Shherbak
  • 2,757
  • 5
  • 34
  • 71

1 Answers1

2

You're right, as you guessed, the ElementAtOrDefault method couldn't be translated to T-SQL, Linq to Entities couldn't recognize it. You can use the Skip and Take methods, something like this:

.Select(y => y.CreatedAt).OrderByDescending(y => y).Skip(1).Take(1)

As an another alternative you can use .ToList() or AsEnumerable methods as well just like this answer https://stackoverflow.com/a/60896583/2946329, but you should be aware, by using them after data is loaded, any further operation is performed using Linq to Objects, on the data already in memory. So if you would care about the performance I am not sure using this approach be a good choice in your case.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109