运行时出错
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/