HOW TO:在 DataContext 層級篩選How to: Filter at the DataContext Level

您可以在 EntitySets 層級篩選 DataContextYou can filter EntitySets at the DataContext level. 這類篩選會套用至所有使用該 DataContext 執行個體的查詢。Such filters apply to all queries done with that DataContext instance.

範例Example

在下列範例中,會使用 DataLoadOptions.AssociateWith(LambdaExpression) 以根據 ShippedDate 來篩選客戶的預先載入訂單。In the following example, DataLoadOptions.AssociateWith(LambdaExpression) is used to filter the pre-loaded orders for customers by ShippedDate.

Northwnd db = new Northwnd(@"northwnd.mdf");
// Preload Orders for Customer.
// One directive per relationship to be preloaded.
DataLoadOptions ds = new DataLoadOptions();
ds.LoadWith<Customer>(c => c.Orders);
ds.AssociateWith<Customer>
    (c => c.Orders.Where(p => p.ShippedDate != DateTime.Today));
db.LoadOptions = ds;

var custQuery =
    from cust in db.Customers
    where cust.City == "London"
    select cust;

foreach (Customer custObj in custQuery)
{
    Console.WriteLine("Customer ID: {0}", custObj.CustomerID);
    foreach (Order ord in custObj.Orders)
    {
        Console.WriteLine("\tOrder ID: {0}", ord.OrderID);
        foreach (OrderDetail detail in ord.OrderDetails)
        {
            Console.WriteLine("\t\tProduct ID: {0}", detail.ProductID);
        }
    }
}
Dim db As New Northwnd("c:\northwnd.mdf")
' Preload Orders for Customer.
' One directive per relationship to be preloaded.
Dim ds As DataLoadOptions = New DataLoadOptions()
ds.LoadWith(Of Customer)(Function(cust) cust.Orders)
ds.AssociateWith(Of Customer)( _
    Function(cust) _
        From ord In cust.Orders _
        Where ord.ShippedDate <> DateTime.Today)

db.LoadOptions = ds

Dim custQuery = From cust In db.Customers _
                Where cust.City = "London" _
                Select cust

For Each custObj In custQuery
    Console.WriteLine("Customer ID: " & custObj.CustomerID)

    For Each ord In custObj.Orders
        Console.WriteLine(vbTab & "Order ID: " & ord.OrderID)

        For Each detail In ord.OrderDetails
            Console.WriteLine(vbTab & vbTab & _
                "Product ID: " & detail.ProductID)
        Next
    Next
Next

另請參閱See also