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

标签 c# entity-framework linq linq-to-sql iqueryable

运行时出错

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.

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;
}

当我引入 OR 时机制开始失败我需要从空的开始。

我如何从一个空集开始,然后在其上构建 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));
}

关于c# - Enumerable.Empty<T>().AsQueryable();此方法支持 LINQ to Entities 基础结构,不应直接从您的代码中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37815309/

相关文章:

linq - LINQ 查询的差异

c# - WebBrowser.Body 总是返回 null

c# - 为什么接收过多参数的 WCF 服务没有中断?

c# - 在 C# 中删除字符串中的重复子字符串

c# - 在 MVC 中合并来自 2 个数据库的数据

c# - 使用 Moq .GetMock 向 Linq 表达式注册 ~1IRepository?

c# - Razor 中变量范围的问题

c# - 无法识别 LINQ to Entities 方法 - 扩展方法样式

entity-framework - 从 EF 中的 EntityType 获取 EntitySet 名称

c# - 两个日期之间有月份差异的Linq查询