在我的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);
}
}
更新
并在规范模式下运行:
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);
}
}
}
这些链在最后生成一个 lambda 表达式,存储库使用它来过滤查询。
当 的每个字段CustomerModel
都有值时,此解决方案可以正常工作,但即使一个属性具有空值或空值,它也不起作用。
如何解决此问题并排除我有 null 或空字符串值的 lambda 表达式?