在我的应用程序中,在
例如,其中一个规范对象(
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 表达式,repository 使用它来过滤查询。
当 CustomerModel
的每个字段都有值时,此解决方案运作良好。但是,如果一个属性具有 null 或空值,则无法正常工作。
我该如何解决这个问题并排除其中值为 null 或空字符串的 lambda 表达式?
AndSpecification
定义,它应该也能正常工作。因为它只是添加了正确的部分,这里是CustomerNameSpecification
的实例。 - CodeNotFound