В моем приложении в функции GetAll
у меня есть параметр, который называется (CustomerModel
). Я использую его, чтобы выполнить некоторую фильтрацию запроса, и я использовал шаблон спецификации, чтобы избежать использования if-else
:
public async Task<List<CustomerModel>> GetAllAsync(CustomerModel customer, Order order = Order.Ascending, int pageIndex = 1, int pageSize = int.MaxValue)
{
var skip = (pageIndex - 1) * pageSize;
var filter = new CustomerNameSpecification(customer)
.And(new CustomerNoSpecification(customer))
.And(new CustomerCompanySpecification(customer))
.And(new CustomerPhoneSpecification(customer))
.And(new CustomerEmailSpecification(customer))
.And(new CustomerAddressSpecification(customer))
.Take(pageSize)
.Skip(skip);
var orderSpecification = new CustomerOrderSpecification(order);
return await _customerRepository.GetAllAsync(filter, orderSpecification);
}
И, например, один из объектов спецификации (CustomerNameSpecification
):
public class CustomerNameSpecification : Specification<Customer>
{
public CustomerModel Customer { get; set; }
public CustomerNameSpecification(CustomerModel customerModel)
{
Customer = customerModel;
}
public override Expression<Func<Customer, bool>> AsExpression()
{
return customerFiler =>
customerFiler.Name.Contains(Customer.Name);
}
}
UPDATE
И операция в спецификации:
public class AndSpecification<T> : Specification<T>
where T : class
{
private readonly ISpecification<T> _left;
private readonly ISpecification<T> _right;
public AndSpecification(ISpecification<T> left, ISpecification<T> right)
{
_left = left;
_right = right;
}
public override Expression<Func<T, bool>> AsExpression()
{
var leftExpression = _left.AsExpression();
var rightExpression = _right.AsExpression();
var parameter = leftExpression.Parameters.Single();
var body = Expression.AndAlso(leftExpression.Body, SpecificationParameterRebinder.ReplaceParameter(rightExpression.Body, parameter));
return Expression.Lambda<Func<T, bool>>(body, parameter);
}
}
}
И эти цепочки создают лямбда-выражение в конце, а хранилище использует его для фильтрации запроса.
Это решение прекрасно работает, когда каждое поле CustomerModel
имеет значение, но оно не работает, даже если одно свойство имеет нулевое или пустое значение.
Как я могу исправить эту проблему и исключить лямбда-выражение, где у меня есть нулевое или пустое строковое значение?