簡體   English   中英

使用 EF Core 過濾包含的屬性?

[英]Filter included property using EF Core?

我目前正在創建一個啤酒網站,我想使用如下簡單查詢按風格過濾啤酒:

IQueryable<Beer> result = this.context.Beers
                                      .Include(b => b.Brewery)
                                      .Include(b => b.Style)
                                      .Include(b => b.Reviews)
                                      .ThenInclude(r => r.User)
                                      .Where(b => b.IsDeleted == false);

if (searchCriteria != null)
{
    if (type == "Name")
    {
        result = result.Where(b => b.Name.Contains(searchCriteria));
    }
    else if (type == "Style")
    {
        result = result.Where(b => b.Style.Name.Contains(searchCriteria));
    }
    else
    {
        result = result.Where(b => b.Brewery.Name.Contains(searchCriteria));
    }
}

但是,當它執行時,我得到 0 結果,因為查詢尚未實現並且 Style 屬性是 null,即使它們已被包含在內。

我該如何解決這個問題?

要實現查詢,只需添加.ToList()

因此,在代碼段的末尾,您可以使用

result.ToList()

不過要小心, Where子句中的某些條件可能會導致潛在的性能問題。 不要忘記創建索引,尤其是當您的數據庫開始變大時。

請注意,您也不應該過早地使用ToList() (在搜索條件之前),因為這意味着在過濾之前獲取 memory 中的所有表。

我還沒有嘗試過,但應該可以先生成您的查詢,然后再通過急切加載最終實現您的查詢。 這樣,您就可以讓數據庫而不是.Net 來完成繁重的工作。

IQueryable<Beer> result = this.context.Beers.Where(b => b.IsDeleted == false);

if (searchCriteria != null)
{
    if (type == "Name")
    {
        result = result.Where(b => b.Name.Contains(searchCriteria));
    }
    else if (type == "Style")
    {
        result = result.Where(b => b.Style.Name.Contains(searchCriteria));
    }
    else
    {
        result = result.Where(b => b.Brewery.Name.Contains(searchCriteria));
    }
}

List<Beer> materialisedResults = result
                                   .Include(b => b.Brewery)
                                   .Include(b => b.Style)
                                   .Include(b => b.Reviews)
                                   .ThenInclude(r => r.User).ToList();

首先,檢查結果中是否有所有數據,然后執行.ToList() 將結果中的所有數據存儲,然后您可以查詢。

var result = this.context.Beers
                         .Include(b => b.Brewery)
                         .Include(b => b.Style)
                         .Include(b => b.Reviews)
                         .ThenInclude(r => r.User)
                         .Where(b => b.IsDeleted == false).ToList();

            if (searchCriteria != null)
            {
                if (type == "Name")
                {
                    result = result.Where(b => b.Name.Contains(searchCriteria));
                }
                else if (type == "Style")
                {
                    result = result.Where(b => b.Style.Name.Contains(searchCriteria));
                }
                else
                {
                    result = resultWhere(b => b.Brewery.Name.Contains(searchCriteria));
                }
            }

暫無
暫無

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

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