Written by:2013/04/09 02:02 PM
Entity Framework's navigation properties maps to the relationships in the database world. In Entity Framework a navigation property on a particular entity is actually a collection of related entities. Consider the following diagram.
Here we have a product that has a relation to various other entities but in particular to SalesOrderDatail via a one-to-many relationship. We also notice that there is a section on each entity called Navigation Properties. Highlighting each navigation property will show us the navigation path. In this case the Navigation Property "SalesOrderDetails" on the Product Entity has a path from Product to SalesOrderDetail via the ProductID property of both the Product and SalesOrderDetail entities.
In Entity Framework the relationship is termed the "Association". This association represents the relationship as found in the underlying database. The association together with the navigation properties will bring back a collection of entities. In this the navigation property SalesOrderDetails of the Product Entity is a Collection of SakesOrderDatails.
We can use regular Linq to navigate through the Associations and retrieve related data. In the example below we are first retrieving a single product, and then we retrieve all the related SalesOrderDetails that are related to that particular product.
using (EFDemoEntities etx = new EFDemoEntities())
var prod = etx.Products.SingleOrDefault(s=> s.ProductID == 707);
var so = prod.SalesOrderDetails;
In fact we could do this in one line:
var so = etx.Products.SingleOrDefault(s=> s.ProductID == 707).SalesOrderDetails;
This would return a Collection of SalesOrderDetails. In fact it is a ICollection<SalesOrderDetail>.
Obviously you could also navigate the other way round. Say you want to see what Products relate to a certain Order Detail. By using the Product Navigation property of the SalesOrderDetail Entity we would easily achieve our goal. The following would return the Product associated or related to the SalesOrderDetail with a ID of 110751.
var prod = etx.SalesOrderDetails.SingleOrDefault(s=> s.SalesOrderDetailID == 110751);
0 comment(s) so far...
Do you want to receive blog updates via e-mail. Then just click on the link below. You will be redirected to Google's feed burner, where you can fill out a form. Supplying your e-mail address.
The subscription is managed entirely by Google's Feedburner. We cannot and do not collect your email address.
Subscribe to The Brave Programmer by Email
Sign up with Disqus to enjoy a surprise box of features