public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string City { get; set; }
public string DisplayName { get { return $"Mr/Miss {Name}"; } }
}
public class PersonSearchCriteria
{
public string Name { get; set; }
public int? Age { get; set; }
public string City { get; set; }
public string DisplayName { get; set; } // 这里的 DisplayName 属性不一定要跟 Person 中的相同
}
public List<Person> SearchPeople(PersonSearchCriteria criteria)
{
using (var context = new MyContext())
{
IQueryable<Person> query = context.People;
if (!string.IsNullOrEmpty(criteria.Name))
{
query = query.Where(x => x.Name.Contains(criteria.Name));
}
if (criteria.Age.HasValue)
{
query = query.Where(x => x.Age == criteria.Age.Value);
}
if (!string.IsNullOrEmpty(criteria.City))
{
query = query.Where(x => x.City == criteria.City);
}
if (!string.IsNullOrEmpty(criteria.DisplayName))
{
query = query.Where(x => x.Name.Contains(criteria.DisplayName.Substring(6))); // 这里使用 Substring 函数截取出名称,并进行关键字查询
}
return query.ToList();
}
}
以上代码通过 AutoMapper 或者手动设置属性映射来关联 Person 模型类和 PersonSearchCriteria 类中的属性,然后在数据查询时,利用属性名进行查询。
public static IQueryable ApplySearchCriteria(this IQueryable query, object searchCriteria) where T : class
{
if (searchCriteria != null)
{
var properties = searchCriteria.GetType().GetProperties();
code
foreach (var property in properties)
{
var value = property.GetValue(searchCriteria, null);
if (value != null)
{
var expression = BuildExpression<T>(property.Name, value);
query = query.Where(expression);
}
}
}
return query;
}
private static Expression<Func<T, bool>> BuildExpression(string propertyName, object value) where T : class
{
var parameter = Expression.Parameter(typeof(T), "xH");
var property = Expression.Property(parameter, propertyName);
var constant = Expression.Constant(value);
var containsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });