【问题标题】:Add Linq.Contains method To a Expression Func<Object,Bool>将 Linq.Contains 方法添加到表达式 Func<Object,Bool>
【发布时间】:2019-05-03 17:10:20
【问题描述】:

我对屏幕截图中的黄色部分有疑问。如果 SelectedGroup 不为空,我想要。除了添加到该表达式的术语之外,添加另一个条件。就是这样。

c => SelectedGroup.Contains (c.CourseGroup.Id) 

选择所有 ID 在该范围内的 SelectedGroup。我写的这个查询不起作用。给出的错误是它不能被翻译成 SQL 查询。我不知道如何解决这个问题。请帮帮我

enter image description here

有关我的代码的更多详细信息 - 这是我的代码存储库:

enter link description here

enter link description here

【问题讨论】:

    标签: entity-framework linq lambda expression ef-core-2.2


    【解决方案1】:

    搭上combine Func,它帮不了你。如果你真的打算返回一个可查询的,你不应该编译你的表达式。

    你可以做的是:

    Expression<Func<Course, bool>> expression = c => (string.IsNullOrEmpty(Title) || EF.Functions.Like(c.CourseTitle, $"%{Title}%")
            && c.IsDeleted == IsDeleted);
    
            switch (statusType)
            {
                case PriceStatusType.All:
                    break;
                case PriceStatusType.Free:
                    queryable = queryable.Where(expression).Where(c => c.CoursePrice < 1000);
                    break;
                case PriceStatusType.Cash:
                    queryable = queryable.Where(expression).Where(c => c.CoursePrice <= MaxPrice && c.CoursePrice >= MinPrice);
                    break;
            }
            if (SelectedGroup != null && SelectedGroup.Any())
            {
                Expression<Func<Course, bool>> e = c => SelectedGroup.Contains(c.CourseGroup.Id);
                queryable = queryable.Where(expression);
                queryable = queryable.Where(c => SelectedGroup.Contains(c.CourseGroup.Id));
    
    
            }
    
            return queryable;
    

    另外,我删除了 Include,因为它没用,如果需要,应该由调用者使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-01
      • 1970-01-01
      相关资源
      最近更新 更多