从lambda表达式中排除空值或空字符串值

4
在我的应用程序中,在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 表达式?

1个回答

2
我该如何解决这个问题并排除空字符串或null值的lambda表达式?例如,对于,您可以使用以下代码来排除空值:
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); 将不会被评估。

谢谢您的回复。我已经尝试过了,但仍然存在同样的问题。我认为规范模式中的 And 操作可能有问题。我已经使用 AndSpecification 更新了主贴。请您检查一下是否有问题? - peyman gilmour
1
即使使用AndSpecification定义,它应该也能正常工作。因为它只是添加了正确的部分,这里是CustomerNameSpecification的实例。 - CodeNotFound
1
糟糕!我的错。我需要将customerFiler更改为customer,以便我们使用IsNullOrWhiteSpace进行检查。再次感谢您的帮助。你救了我的一天! - peyman gilmour

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接