使用 BatchOr / BatchAnd 查询


  BatchOr 或 BatchAnd 可以将一个数组或列表里的元素,使用特定的表达式进行 Or 或 And 拼接。

[TestMethod]
public void TestBatchOr()
{
    var countries = new string[] { "France", "Spain" };
    using (var db = new DbContext())
    {
        var list = db.Customers.BatchOr(countries, (s, t) => s.Country.Contains(t)).ToList();
        Assert.AreEqual(16, list.Count);
    }
}

[TestMethod]
public void TestBatchAnd()
{
    var countries = new string[] { "France", "Spain" };
    using (var db = new DbContext())
    {
        var list = db.Customers.BatchAnd(countries, (s, t) => s.Country.Contains(t)).ToList();
        Assert.AreEqual(0, list.Count);
    }
}

  以上 TestBatchOr 示例中,实际解析成的 SQL 为:

select * from customers where country like '%France%' or country like '%Spain%'

  而 TestBatchAnd 示例,实际解析成的 SQL 为:

select * from customers where country like '%France%' and country like '%Spain%'

  这样你可能就对这两个扩展方法有更深刻的认识了。