Enumerable.Empty ()AsQueryable已(); 此方法支持LINQ to Entities基础结构,不应在代码中直接使用
我收到运行时错误
此方法支持LINQ to Entities基础结构,不应在代码中直接使用。
描述:执行当前Web请求期间发生未处理的exception。 请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。
exception详细信息:System.InvalidOperationException:此方法支持LINQ to Entities基础结构,不应在代码中直接使用。
我试图通过在所有搜索字段上添加所有匹配的记录(将执行OR
而不是AND
)来生成查询而不是对每个搜索条件进行过滤。
public static IQueryable ApplySearch(this IQueryable queryable, SearchModel search) where T : class { var results = Enumerable.Empty().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().AsQueryable();
时,机制开始失败var results = Enumerable.Empty().AsQueryable();
我需要从空洞的东西开始。
如何从空集开始,然后在顶部构建Linq-to-sql结果?
你可以通过只有你所拥有的联合结果来重构代码以不需要空集:
public static IQueryable ApplySearch (this IQueryable queryable, SearchModel search) where T : class { var subQueries = new List>(); 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().AsQueryable();
至
var results = queryable.Where(o => false);