Created
February 5, 2012 18:48
-
-
Save MikeLarned/1747148 to your computer and use it in GitHub Desktop.
Search IQuery Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Linq.Expressions; | |
using MedTest.Infrastructure.Entitys; | |
using NHibernate; | |
using NHibernate.Linq; | |
using MedTest.Infrastructure.NHibernate; | |
namespace MedTest.Core.Domain.Employees.Query | |
{ | |
public class GetEmployeeSearchQuery : IQuery<EmployeePagedList> | |
{ | |
private readonly Guid _companyId; | |
private string _searchTerm; | |
private readonly int _skip; | |
private readonly int _take; | |
public GetEmployeeSearchQuery(Guid companyId, int skip, int take) | |
{ | |
_companyId = companyId; | |
_skip = skip; | |
_take = take; | |
} | |
public GetEmployeeSearchQuery WithSearchTerm(string searchTerm) | |
{ | |
_searchTerm = searchTerm; | |
return this; | |
} | |
public EmployeePagedList Execute(ISession session) | |
{ | |
var query = session.Query<Employee>() | |
.Where(x => x.Company.Id == _companyId) | |
.Where(GetFilters()) | |
.Skip((_skip - 1)*_take) | |
.Take(_take) | |
.Fetch(x => x.Company); | |
var countQuery = session.Query<Employee>() | |
.Where(x => x.Company.Id == _companyId) | |
.Where(GetFilters()); | |
return new EmployeePagedList | |
{ | |
Employees = query.ToList(), | |
Total = countQuery.Count() | |
}; | |
} | |
private Expression<Func<Employee, bool>> GetFilters() | |
{ | |
if (!string.IsNullOrEmpty(_searchTerm)) | |
{ | |
var terms = _searchTerm.Split(' '); | |
Expression<Func<Employee, bool>> expression = x => x.Last.Contains(_searchTerm.Trim()) || x.First.Contains(_searchTerm.Trim()) || x.Number.Contains(_searchTerm.Trim()); | |
foreach(var term in terms) | |
{ | |
var s = term.Trim(); | |
expression = expression.Or(x => x.Last.Contains(s) || x.First.Contains(s) || x.Number.Contains(s)); | |
} | |
return expression; | |
} | |
return x => true; | |
} | |
} | |
public class EmployeePagedList | |
{ | |
public IEnumerable<Employee> Employees { get; set; } | |
public int Total { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment