使用 AssertWhere 查询


  在查询参数比较多的时候,你可能会被这样的场景所困扰:

[TestMethod]
public void TestGeneralWhere()
{
    using (var db = new DbContext())
    {
        DateTime? startTime = null;
        DateTime? endTime = null;
        var state = 0;

        IQueryable<Orders> query = db.Orders;
        if (startTime != null)
        {
            query = query.Where(s => s.OrderDate >= startTime);
        }
        if (endTime != null)
        {
            query = query.Where(s => s.OrderDate <= endTime);
        }
        if (state == 0)
        {
            query = query.Where(s => s.RequiredDate == DateTime.Now);
        }
        else
        {
            query = query.Where(s => s.OrderState == state);
        }
    }
}

  这样的代码不管是书写还是阅读都是非常费力,相信浮躁的你内心肯定会有一万个草泥马飞过。

  AssertWhere 可先判断外部条件是否成立,然后分别应用不同的 lambda 表达式,这在查询条件比较多的情况下,能够提高代码的可读性和可维护性。

[TestMethod]
public void TestAssertWhere()
{
    using (var db = new DbContext())
    {
        DateTime? startTime = null;
        DateTime? endTime = null;
        var state = 0;

        var list = db.Orders
            .AssertWhere(startTime != null, s => s.OrderDate >= startTime)
            .AssertWhere(endTime != null, s => s.OrderDate <= endTime)
            .AssertWhere(state == 0, s => s.RequiredDate == DateTime.Now, s => s.OrderState == state);
    }
}

  AssertWhere 后面有两个 lambda 表达式参数。当条件成立时,应用 isTruePredicate 进行查询,不成立时应用 isFalsePredicate 查询。