Database Reference
In-Depth Information
Console.WriteLine("SKU\tDescription\tQty\tPrice");
Console.WriteLine("---\t-----------\t---\t-----");
foreach (var oi in order.OrderItems)
{
Console.WriteLine("{0}\t{1}\t{2}\t{3}", oi.Item.SKU,
oi.Item.Description, oi.Count.ToString(),
oi.Item.Price.ToString("C"));
}
}
}
The following is the output from the code shown in Listing 2-4.
Order # 1, ordered on 1/18/2010
SKU Description Qty Price
---- ----------- --- ------
1729 Backpack 1 $29.97
1847 Camp Stove 1 $43.99
2929 Water Filter 3 $13.97
After we create an instance of our database context, we create and initialize an Order entity as well as the items
and order items for the order. We connect the order with the items by initializing the OrderItem entities with the
instances of the Order entity and the Item entity. We use the Add() method to add the order to the context.
With the object graph complete and the order added to the context, we update the database with the
SaveChanges() method.
To retrieve the entities from the database, we create a fresh instance of the context and iterate through the
context.Orders collection. For each order (well, we just have one in this example), we print the order detail and
we iterate through the entity collection on the OrderItems navigation property. These instances of the OrderItem
entity type give us access to the Count scalar property (the payload) directly, and each item on the order via the Item
navigation property. Going through the OrderItems entity to get to the items is the “extra” hop that is the cost of
having a payload in the link table (OrderItems, in our example) in a many-to-many relationship.
Best Practice
Unfortunately, a project that starts out with several payload-free many-to-many relationships often ends up with
several payload-rich many-to-many relationships. Refactoring a model, especially late in the development cycle,
to accommodate payloads in the many-to-many relationships can be tedious. Not only are additional entities
introduced, but the queries and navigation patterns through the relationships change as well. Some developers
argue that every many-to-many relationship should start off with some payload, typically a synthetic key, so that the
inevitable addition of more payload has significantly less impact on the project.
So here's the best practice: If you have a payload-free many-to-many relationship and you think there is some
chance that it may change over time to include a payload, start with an extra identity column in the link table. When
you import the tables into your model, you will get two one-to-many relationships, which means the code you write
and the model you have will be ready for any number of additional payload columns that come along as the project
matures. The cost of an additional integer identity column is usually a pretty small price to pay to keep the model
more flexible.
 
Search WWH ::




Custom Search