【问题标题】:How to use multi expression methods in Entity Framework query [duplicate]如何在实体框架查询中使用多表达式方法[重复]
【发布时间】:2017-08-09 07:36:28
【问题描述】:

我在我的应用程序中多次使用相同的 EF 查询,所以我需要这样的东西:

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;
}

我想在多个查询中使用相同的逻辑,例如:

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

有人对此有任何想法吗?如何在表达式方法之间使用 ANDOR 逻辑?

【问题讨论】:

  • 如果只需要And他们一起,只需再添加一个Where子句,例如:context.Orders.Where(StudentIsActive()).Where(StudentIsBusy())
  • @DavidG 谢谢,AND 的好解决方案

标签: c# entity-framework


【解决方案1】:

我不在家,所以我无法测试它,我认为您可以将这些方法传输到 IQueryable 的扩展方法中,如下所示:

  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);
        }

    }

并像这样使用它:

context.Orders.StudentIsActive().IsBusy().ToList();

【讨论】:

  • 这只是“和”而不是“或”,和我上面的评论也没有什么不同。
【解决方案2】:

我通常发现And/OrExpressions 一起使用的最简单方法是使用LinqKit。引用该库后,您可以执行以下操作:

//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);

【讨论】:

  • 投反对票的人能解释一下吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-30
  • 1970-01-01
  • 1970-01-01
  • 2016-12-25
  • 2020-03-29
  • 1970-01-01
  • 2018-11-16
相关资源
最近更新 更多