Database Reference
In-Depth Information
Figure 2-13. Two one-to-many associations from a many-to-many relationship with payload
How It Works
As we saw in the previous recipe, for a many-to-many relationship with no payload, the model is clean and simple to
navigate. Because Entity Framework does not support the notion of payloads on associations, it surfaces the link table
as an entity with two one-to-many associations to the related entities. In this case, the OrderItem table is represented
not as an association, but as an entity type with a one-to-many association to Order and a one-to-many association
to Item. In the previous recipe, the payload-free link table did not translate into an entity type in the model. Instead,
it became part of the many-to-many association.
The addition of a payload requires an additional hop through the entity representing the link table to retrieve the
related items. This is illustrated in code in Listing 2-4.
Listing 2-4. Inserting into and Retrieving from the Model
using (var context = new EF6RecipesContext())
{
var order = new Order { OrderId = 1,
OrderDate = new DateTime(2010, 1, 18) };
var item = new Item { SKU = 1729, Description = "Backpack",
Price = 29.97M };
var oi = new OrderItem { Order = order, Item = item, Count = 1 };
item = new Item { SKU = 2929, Description = "Water Filter",
Price = 13.97M };
oi = new OrderItem { Order = order, Item = item, Count = 3 };
item = new Item { SKU = 1847, Description = "Camp Stove",
Price = 43.99M };
oi = new OrderItem { Order = order, Item = item, Count = 1 };
context.Orders.Add(order);
context.SaveChanges();
}
using (var context = new EF6RecipesContext())
{ foreach (var order in context.Orders)
{
Console.WriteLine("Order # {0}, ordered on {1}",
order.OrderId.ToString(),
order.OrderDate.ToShortDateString());
 
Search WWH ::




Custom Search