1

I use same EF query multiple times in my application so I need something like this:

private Expression<Func<Student, bool>> StudentIsActive()
{
    return (x) => !x.IsDeleted && x.ItemsNumber > 0 && x.Sort > 0 && x.Status == StudentStatus.Active;
}

private Expression<Func<Student, bool>> StudentIsBusy()
{
    return (x) => x.Mode == ModeType.Busy && x.Jobs.Count() > 0;
}

I want to use same logic in multiple of my queries, like:

 var students = context.Orders.Where(x => StudentIsActive() && StudentIsBusy()).ToList();

Does any one have any idea about this? how could I use AND or OR logic between expression methods?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Saeid
  • 13,224
  • 32
  • 107
  • 173
  • 1
    If you only need to `And` them together, just add another `Where` clause, for example: `context.Orders.Where(StudentIsActive()).Where(StudentIsBusy())` – DavidG Mar 17 '17 at 16:42
  • @DavidG Thanks, good solution for AND – Saeid Mar 17 '17 at 16:53

2 Answers2

0

I am not in home so I cant test itt buy I think you can transport these methods into extensions methods of IQueryable like this:

  public static class Ext
    {
       public static IQueryable<MainActivity.Student> StudentIsActive(this IQueryable<MainActivity.Student> @this)
        {
            return @this.Where(x => !x.IsDeleted && x.ItemsNumber > 0 && x.Sort > 0 && x.Status == StudentStatus.Active);
        }

        public static IQueryable<MainActivity.Student> IsBusy(this IQueryable<MainActivity.Student> @this)
        {
            return @this.Where(x.Mode == ModeType.Busy && x.Jobs.Count() > 0);
        }

    }

And use it like:

context.Orders.StudentIsActive().IsBusy().ToList();
miechooy
  • 3,178
  • 12
  • 34
  • 59
0

I usually find the easiest way to And/Or Expressions together is to use LinqKit. Once you've referenced that library you can do this:

//Or
var orPredicate = PredicateBuilder.Or(StudentIsActive(), StudentIsBusy());
var orders1 = context.Orders.AsExpandable().Where(orPredicate);

//And
var andPredicate = PredicateBuilder.And(StudentIsActive(), StudentIsBusy());
var orders2 = context.Orders.AsExpandable().Where(andPredicate);
DavidG
  • 113,891
  • 12
  • 217
  • 223