0

I have something that currently looks like this and works in EF Core:

DbContext.Computers.OrderByDirection(state.SortDirection, 
    x => x.Actions.FirstOrDefault(y => y.GetType() == typeof(PingAction) && 
    y.History.Any(z => z.Status == Status.Succeeded && 
    (DateTime.Now - z.WhenExecuted).TotalMinutes < 10)))

However I also need to use the x function elsewhere and don't want to hard code it multiple times. How can I save that function to a variable or something and still allow it to work with the server sided filtering of EF core since of course this will be translated to SQL?

UPDATE

Signatures for OrderByDirection:

public static IOrderedEnumerable<TSource> OrderByDirection<TSource, TKey>(this IEnumerable<TSource> source, SortDirection direction, Func<TSource, TKey> keySelector)
public static IOrderedQueryable<TSource> OrderByDirection<TSource, TKey>(this IQueryable<TSource> source, SortDirection direction, Expression<Func<TSource, TKey>> keySelector)
5
  • Is OrderByDirection a custom extension method? You can probably save the function definition in an Expression and forward that to this method and use it elsewhere if you have to. learn.microsoft.com/en-us/dotnet/csharp/programming-guide/… Commented Feb 17, 2022 at 14:14
  • @fbede Ooops, didn't realise it but you're right, it belongs to MudBlazor which I'm using of course. Commented Feb 17, 2022 at 14:50
  • @fbede what would my expression look like and how would I pass it? Commented Feb 17, 2022 at 14:51
  • can you add the method header of OrderByDirection? Especially the parameter types. Commented Feb 17, 2022 at 15:10
  • @fbede added it yesterday :) Commented Feb 18, 2022 at 14:58

1 Answer 1

1

I think you could extract the expression into a variable similarly to this:

(I am only guessing the class names by your property names, they aren't obvious from your code):

Expression<Func<Computer, Action>> expression = x => x.Actions.FirstOrDefault(
    action => action.GetType() == typeof(PingAction) && action.History.Any(
        history => history.Status == Status.Succeeded && (DateTime.Now - z.WhenExecuted).TotalMinutes < 10));

DbContext.Computers.OrderByDirection(state.SortDirection, expression);

then this expression can be reused elsewhere.

Sign up to request clarification or add additional context in comments.

Comments

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.