在我的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);
}
}
}
這些鏈在最後創建一個lambda表達式,存儲庫使用它來過濾查詢。
當CustomerModel
每個字段都有值時,此解決方案可以正常工作,但即使一個屬性具有null值或空值,它也不起作用。
如何修復此問題並排除lambda表達式,其中我有一個空值或空字符串值?
如何修復此問題並排除lambda表達式,其中我有一個空值或空字符串值?
例如CustomerNameSpecification
,要排除空值,您可以使用代碼:
public override Expression<Func<Customer, bool>> AsExpression()
{
return customerFiler => string.IsNullOrWhiteSpace(customerFiler.Name) ||
customerFiler.Name.Contains(Customer.Name);
}
如果string.IsNullOrWhitespace(customerFiler.Name)
返回true
則customerFiler.Name.Contains(Customer.Name);
不會被評估。