全局筛选


  可以使用 EntityContext 的 Apply 方法制定全局的筛选条件,后续相关的仓储查询将被限制在此条件内。

  如下面的示例中,可以为 Customers 查询指定默认的筛选条件,之后的查询不需要再指定。

[TestMethod]
public void TestApply()
{
    using (var db = new DbContext())
    {
        db.Apply<Customers>(u => u.Where(s => s.CustomerID == "ALFKI"));

        var customers = db.Customers
            .ToList();

        //不加限定条件为 88 条数据
        Assert.AreEqual(1, customers.Count);
    }
}

  可以使用 Associate 方法制定子实体集筛选条件。

[TestMethod]
public void TestAssociate()
{
    using (var db = new DbContext())
    {
        db.Associate<Customers>(s => s.Orderses.Where(o => o.OrderDate >= DateTime.Now));

        var customers = db.Customers
            .Where(c => c.CustomerID == "ALFKI")
            .Select(c => new
                {
                    CustomerID = c.CustomerID,
                    FilteredOrdersCount = c.Orderses.Count()
                })
            .ToList();

        Assert.AreEqual(1, customers.Count);

        //未筛选前是 7 条数据
        Assert.AreEqual(0, customers[0].FilteredOrdersCount);
    }
}

  另外,还可以使用 EntityRepository<T> 的 Associate 方法,效果是和上面一样的。

[TestMethod]
public void TestAssociate()
{
    using (var db = new DbContext())
    {
        var customers = db.Customers.Associate(s => s.Orderses.Where(o => o.OrderDate >= DateTime.Now))
            .Where(c => c.CustomerID == "ALFKI")
            .Select(c => new
                {
                    CustomerID = c.CustomerID,
                    FilteredOrdersCount = c.Orderses.Count()
                })
            .ToList();

        Assert.AreEqual(1, customers.Count);

        //未筛选前是 7 条数据
        Assert.AreEqual(0, customers[0].FilteredOrdersCount); 
    }
}