在我的应用程序的 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 或空值,它也不起作用。
我该如何解决这个问题并排除我有 null 或空字符串值的 lambda 表达式?
最佳答案
How can I fix this problem and exclude lambda expression where I have a null or empty string value?
例如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);
将不会评估。
关于c# - 从 lambda 表达式中排除 null 或空字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50210550/