Home > Software design >  EF Core Filtering
EF Core Filtering

Time:02-23

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)

CodePudding user response:

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.

  • Related