簡體   English   中英

如何使用 DBSet 上的關鍵字列表進行過濾

[英]How to filter with a list of keywords on a DBSet

我的 Controller 中有:

var query = _context.Jobs.Where(x => x.Category.Equals(filterParams.Category) ||
filterParams.Query.Any(val => x.Title.Contains(val)));

這是FilterParams class

    public class FilterParams
    {
        public string[] Query { get; set; }
        public CategoryEnum Category { get; set; }
    }

Category上的過濾器工作正常,但Title部分沒有。 我嘗試了很多不同的方法,但它從來沒有給我預期的行為:

給定以下filterParams.Query (string[]): ['FOO', 'BAR'] 我希望它返回帶有標題的實體,例如: foo alice bar; 富吧鮑勃

我們如何根據數組進行過濾?

我得到的錯誤是:

System.InvalidOperationException: The LINQ expression 'val => EntityShaperExpression: 
    ynyn_be.Models.Job
    ValueBufferExpression: 
        ProjectionBindingExpression: EmptyProjectionMember
    IsNullable: False
.Title.Contains(val)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'.

我不明白,因為在過濾器之后,我正在使用ToListAsync執行我的Skip()Take() ,那么它為什么要我再做一次呢? 我很困惑。

我找到了一種解決方法,它可能是暫時的,直到我找到一種更清潔的方法,如果它可以幫助其他人,仍然會分享它

                IQueryable<Job> query = _context.Jobs;

                if (filterParams.Category != null)
                {
                    query = query.Where(x => x.Category.Equals(filterParams.Category));
                } 

                foreach (var key in filterParams.Query)
                {
                    query = query.Where(x => 
                        x.Title.ToLower().Contains(key) ||
                        x.Description.ToLower().Contains(key));
                }

我只是遍歷我的關鍵字數組並將它們添加到我的IQueryable中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM