Before: (Linq expression)
results = from u in ctx.ActiveUsers
where (u.CompanyID != 1 &&
(u.LastName.ToLower().Contains(searchString)
|| u.Email.ToLower().Contains(searchString)
|| u.Company.Name.ToLower().Contains(searchString)))
orderby u.LastName, u.FirstName
select new Employee
{
ID = u.ID,
FirstName = u.FirstName,
LastName = u.LastName,
Email = u.Email,
CompanyName = u.Company.Name,
CompanyID = u.CompanyID.ToString()
};
After: (Lambda expression)
results = ctx.ActiveUsers
.Where(Employee.GetExpression(searchString))
.OrderBy(u => u.LastName ).ThenBy(u => u.FirstName)
.Select(u => new Employee {
ID = u.ID
, FirstName = u.FirstName
, LastName = u.LastName
, Email = u.Email
, CompanyName = u.Company.Name
, CompanyID = u.CompanyID.ToString() });
plus this to keep the where expression the same on the count:
private static Expression<Func<User, bool>> GetExpression(string searchString)
{
Expression<Func<User, bool>> p = (u => u.CompanyID != 1 &&
(u.LastName.ToLower().Contains(searchString)
|| u.Email.ToLower().Contains(searchString)
|| u.Company.Name.ToLower().Contains(searchString)));
return p;
}
so that GetExpression can be used here to make sure that our count query is the same as the select
public static int GetCustomerCount()
{
UserContext ctx = new UserContext();
int totalRecords;
string searchString = SearchString;
totalRecords = ctx.ActiveUsers.Count(Employee.GetExpression(searchString));
return totalRecords;
}
No comments:
Post a Comment