Entity Framework 5 – Navigation Properties
Apr9Written 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:
using (EFDemoEntities etx = new EFDemoEntities())
{
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.
using (EFDemoEntities etx = new EFDemoEntities())
{
var prod = etx.SalesOrderDetails.SingleOrDefault(s=> s.SalesOrderDetailID == 110751);
prod.Dump();
}
Related Reading:
blog comments powered by