[英]Returning Enumerable.Empty<T>().AsQueryable() a bad idea?
[英]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.