Database Reference
In-Depth Information
public DbSet<Order> Orders { get; set; }
public DbSet<OrderItem> OrderItems { get; set; }
}
Next, add an App.Config class to the project and add the code from Listing 5-25 to it under the
ConnectionStrings section.
Listing 5-25. Connection String
<connectionStrings>
<add name="Recipe10ConnectionString"
connectionString="Data Source=.;
Initial Catalog=EFRecipes;
Integrated Security=True;
MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
In Figure 5-25 , we have a simple model composed of an order and the products (collection of OrderItems) shipped
for the order. One way to get the total amount for the order is to use the Load() method to load the entire collection of
order items and then iterate through this collection, calculating the sum of the amount for each order item.
Another way to get the same result is to push the iteration to the database, letting it compute the total amount.
The advantage to this second approach is that we avoid the potentially costly overhead of materializing each order
item for the sole purpose of summing the total order amount. To implement this second approach, follow the pattern
shown in Listing 5-26.
Listing 5-26. Applying an Aggregate Operator on Related Entities Without Loading Them
using (var context = new EFRecipesEntities())
{
var order = new Order { CustomerName = "Jenny Craig", OrderDate = DateTime.Parse("3/12/2010") };
var item1 = new OrderItem { Order = order, Shipped = 3, SKU = 2827, UnitPrice = 12.95M };
var item2 = new OrderItem { Order = order, Shipped = 1, SKU = 1918, UnitPrice = 19.95M };
var item3 = new OrderItem { Order = order, Shipped = 3, SKU = 392, UnitPrice = 8.95M };
order.OrderItems.Add(item1);
order.OrderItems.Add(item2);
order.OrderItems.Add(item3);
context.Orders.Add(order);
context.SaveChanges();
}
using (var context = new EFRecipesEntities())
{
// Assume we have an instance of Order
var order = context.Orders.First();
Search WWH ::




Custom Search