我读过很多关于LINQ和Where子句的文章。我几乎没有尝试创建良好的PagedList机制。此时从数据库中获取100个对象需要大约3秒进行查询,但是当我添加Where子句时,它会慢慢减慢到大约10-13秒。
我的代码:
public IPagedList<WsPolice> GetPoliciesListLINQ(NavigationModule navModule, List<int> userChildren)
{
// IQueryable object
var query = _session.Query<WsPolice>();
// right filters
query = GetPolicyCriteriaLINQ(query, navModule, userChildren);
// search query
query = AddSearchToQuery(query, navModule);
// order
query = query.CustomOrder(navModule.CurrentSortAtrribute ?? navModule.DefaultSortAttribute, navModule.isAsceding.HasValue && navModule.isAsceding.Value);
// pagedlist
var finalList = query.ToPagedList(navModule.Page.Value, navModule.ItemsOnPage.Value);
return finalList;
}
AddSearchToQuery函数会产生问题:
public IQueryable<WsPolice> AddSearchToQuery(IQueryable<WsPolice> query, NavigationModule navModule)
{
// add query if string is not null
if (!string.IsNullOrEmpty(navModule.CurrentSearchString))
{
query = query.Where(GetPolicySearchExpression(navModule.CurrentSearchString));
}
}
public Expression<Func<WsPolice, bool>> GetPolicySearchExpression(string query)
{
query = query.ToLower();
return
x =>
x.policyDateEnd.ToString().ToLower().Contains(query) ||
x.policyDate.ToString().ToLower().Contains(query) ||
x.policyNr.ToLower().Contains(query) ||
x.policyAmount.ToString().ToLower().Contains(query) ||
x.policyDue.ToString().ToLower().Contains(query) ||
x.policyCollectionAmount.ToString().ToLower().Contains(query) ||
x.wsUsers.userName.ToLower().Contains(query) ||
x.wsUsers.userSname.ToLower().Contains(query) ||
x.wsUsers.userCompanyName.ToLower().Contains(query) ||
x.wsUsersIssuing.userName.ToLower().Contains(query) ||
x.wsUsersIssuing.userSname.ToLower().Contains(query) ||
x.wsUsersIssuing.userCompanyName.ToLower().Contains(query) ||
x.wsUsersIssuing.userAgentId.ToLower().Contains(query) ||
x.wsVehicles.vehicleRegNumber.ToLower().Contains(query) ||
x.wsVehicles.vehicleBrand.ToLower().Contains(query) ||
x.wsVehicles.vehicleModel.ToLower().Contains(query) ||
x.wsUsers.userPesel.ToLower().Contains(query) ||
x.wsUsers.userRegon.ToLower().Contains(query) ||
x.wsVehicles.VehicleCoowners.Select(y => (y.CoownerPesel ?? "").ToLower()).Any(z => z.Contains(query)) ||
x.wsVehicles.VehicleCoowners.Select(y => (y.CoownerName ?? "").ToLower()).Any(z => z.Contains(query)) ||
x.wsVehicles.VehicleCoowners.Select(y => (y.CoownerSname ?? "").ToLower()).Any(z => z.Contains(query)) ||
x.WsPolicyAliases.Select(y => (y.AliasName ?? "").ToLower()).Any(z => z.Contains(query));
}
正如许多文章建议的那样,我使用Expression<Func<T, bool>>
因为它比Func<T, bool>
更快。我的对象总是IQueryable,而不是IEnumerable。我究竟做错了什么?我试图用一对多的关系来评论这些行,但它并没有改变性能。
我使用了NhibernateProfiler并得到了这个:link,最后一个AND语句需要7秒。