Enumerable.Empty<T>().AsQueryable();此方法支持 LINQ to Entities 基础结构,不应直接从您的代码中使用

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

我收到运行时错误

This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code.

我正在尝试生成查询,而不是过滤每个搜索条件,而是通过在所有搜索字段上添加所有匹配的记录(会 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));
}

我用过的临时 hack

是从

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

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