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
  • 704,970
  • 168
  • 1,303
  • 1,425
Saeid
  • 12,776
  • 31
  • 100
  • 168
  • 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
  • 2,893
  • 11
  • 32
  • 55
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
  • 104,599
  • 10
  • 205
  • 202