簡體   English   中英

Enumerable.Empty<t> ().AsQueryable(); 此方法支持 LINQ 到實體基礎設施,不打算直接從您的代碼中使用</t>

[英]Enumerable.Empty<T>().AsQueryable(); This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code

我收到運行時錯誤

此方法支持 LINQ 到實體基礎設施,並且不打算直接從您的代碼中使用。

說明:在執行當前 web 請求期間發生未處理的異常。 請查看堆棧跟蹤以獲取有關錯誤及其源自代碼的位置的更多信息。

異常詳細信息:System.InvalidOperationException:此方法支持 LINQ 到 Entities 基礎架構,並且不打算直接從您的代碼中使用。

我正在嘗試生成查詢,而不是通過在所有搜索字段上添加所有匹配記錄來過濾每個搜索條件(將執行OR而不是AND )。

public static IQueryable<T> ApplySearch<T>(this IQueryable<T> queryable, SearchModel search) where T : class 
{
    var results = Enumerable.Empty<T>().AsQueryable();
    if (search != null)
    {
        if (search.PolicyNumber.HasValue && typeof (IPolicyNumber).IsAssignableFrom(queryable.ElementType))
        {
            results = results.Union(queryable.SearchByPolicyNumber(search));
        }

        if (search.UniqueId.HasValue && typeof (IUniqueId).IsAssignableFrom(queryable.ElementType))
        {
            results = results.Union(queryable.SearchByUniqueId(search));
        }

        if (!string.IsNullOrWhiteSpace(search.PostCode) && typeof(IPostCode).IsAssignableFrom(queryable.ElementType))
        {
            results = results.Union(queryable.SearchByPostCode(search));
        }
    }

    return results;
}

當我引入var results = Enumerable.Empty<T>().AsQueryable();時,機制開始失敗我需要從空的東西開始。

如何從一個空集開始,然后在頂部構建 Linq-to-sql 結果?

你可以通過只有你所擁有的聯合結果來重構代碼,而不需要一個空集:

public static IQueryable<T> ApplySearch<T>(this IQueryable<T> queryable, SearchModel search) where T : class 
{
    var subQueries = new List<IQueryable<T>>();
    if (search != null)
    {
        if (search.PolicyNumber.HasValue && typeof (IPolicyNumber).IsAssignableFrom(queryable.ElementType))
        {
            subQueries.Add(queryable.SearchByPolicyNumber(search));
        }

        if (search.UniqueId.HasValue && typeof (IUniqueId).IsAssignableFrom(queryable.ElementType))
        {
            subQueries.Add(queryable.SearchByUniqueId(search));
        }

        if (!string.IsNullOrWhiteSpace(search.PostCode) && typeof(IPostCode).IsAssignableFrom(queryable.ElementType))
        {
            subQueries.Add(queryable.SearchByPostCode(search));
        }
    }

    return subQueries.DefaultIfEmpty(queryable)
        .Aggregate((a, b) => a.Union(b));
}

我曾經使用的臨時黑客

是改變

var results = Enumerable.Empty<T>().AsQueryable();

var results = queryable.Where(o => false);
var results = queryable.Take(0);

如果結果至少有一個聯合,則忽略第一組空結果,生成的 SQL 查詢不包含它。 所以如果你用這組空結果調用Union ,在生成的 SQL 中,根本沒有 union。 但是如果你不調用聯合,那么它仍然會調用數據庫,即使有WHERE (1=0) 在這種情況下,最好返回一個空的可枚舉或列表以避免不必要的 DB 調用。

暫無
暫無

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

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