Database Reference
In-Depth Information
// Get the total order amount
var amt = context.Entry(order)
.Collection(x => x.OrderItems)
.Query()
.Sum(y => y.Shipped * y.UnitPrice);
Console.WriteLine("Order Number: {0}", order.OrderId);
Console.WriteLine("Order Date: {0}", order.OrderDate.ToShortDateString());
Console.WriteLine("Order Total: {0}", amt.ToString("C"));
}
The following is the output of the code in Listing 5-26:
Order Number: 6
Order Date: 3/12/2010
Order Total: $85.65
How It Works
In Listing 5-26, we implement explicit loading and start with the Entry() method that is exposed by the DbContext
object. Entry() accepts an argument of Order, which represents the parent entity that we wish to query. Entry()
provides a wealth of information about the Order, including access to related entity objects via the Collection() and
Reference() methods.
In the example above, we query related Order Items entities by chaining the Collection() method and passing
in the navigation property, OrderItems, as a parameter. The associated Query() method from the DbCollectionEntry
class generates a query to load the Order Item objects from the underlying data store.
Finally, we apply the Sum() LINQ extension method, passing in a lambda expression that calculates the item
total. The resulting sum over the collection is the order total. This entire expression is converted to the appropriate
store layer commands and executed in the storage layer, saving the cost of materializing each order item.
This simple example demonstrates the flexibility of combining explicit loading with the Entry() and Query()
method to modify the query used to retrieve the underlying associated entity collection (OrderItems). In this case, we
leveraged the query, summing the amounts for OrderItems that are related to the first order without actually loading
the collection.
5-11. Testing Whether an Entity Reference or Entity Collection
Is Loaded
Problem
You want to test whether the related entity or entity collection is loaded in the context. Additionally, you want to
implement the Code-First approach for Entity Framework 6 to manage data access.
Solution
Suppose that you have a model like the one shown in Figure 5-26 .
 
 
Search WWH ::




Custom Search