Database Reference
In-Depth Information
The code in Listing 6-6 inserts a few related products and retrieves the related products. To retrieve all of the
related products for a given product, we need to traverse both the RelatedProducts navigation property and the
OtherRelatedProducts navigation property.
Tent is related to Ground Cover through the RelatedProducts navigation property because we added Ground
Cover to Tent's RelatedProducts collection. Pole is related to Tent through Tent's OtherRelatedProducts collection
because we added Tent to Pole's RelatedProducts collection. The associations go both ways. In one direction,
it's a related product. In the other direction, it's an OtherRelatedProduct.
Listing 6-6. Retrieving the Related Products
using (var context = new EF6RecipesContext())
{
var product1 = new Product { Name = "Pole", Price = 12.97M };
var product2 = new Product { Name = "Tent", Price = 199.95M };
var product3 = new Product { Name = "Ground Cover", Price = 29.95M };
product2.RelatedProducts.Add(product3);
product1.RelatedProducts.Add(product2);
context.Products.Add(product1);
context.SaveChanges();
}
using (var context = new EF6RecipesContext())
{
var product2 = context.Products.First(p => p.Name == "Tent");
Console.WriteLine("Product: {0} ... {1}", product2.Name,
product2.Price.ToString("C"));
Console.WriteLine("Related Products");
foreach (var prod in product2.RelatedProducts)
{
Console.WriteLine("\t{0} ... {1}", prod.Name, prod.Price.ToString("C"));
}
foreach (var prod in product2.OtherRelatedProducts)
{
Console.WriteLine("\t{0} ... {1}", prod.Name, prod.Price.ToString("C"));
}
}
The output of Listing 6-6 is as follows:
Product: Tent ... $199.95
Related Products
Ground Cover ... $29.95
Pole ... $12.97
The code in Listing 6-6 retrieves only the first level of related products. A transitive relationship is one that spans
multiple levels, like a hierarchy. If we assume that the “related products” relationship is transitive, we might want to
form the transitive closure. The transitive closure would be all of the related products regardless of how many hops
away they may be. In an eCommerce application, product specialists could create the first level of related products.
Additional levels could be derived by computing the transitive closure. The end result would allow the application to
show the familiar “…you may also be interested in …” message that we often see during the checkout process.
In Listing 6-7, we use a recursive method to form the transitive closure. In traversing both the RelatedProducts
and OtherRelatedProducts associations, we need to be careful not to get stuck in a cycle. If product A is related to B,
 
Search WWH ::




Custom Search