This project is read-only.

Dependency Walking and Lazy Loading

A very useful feature of the generated framework is the ability to load an object and “walk” its relationships. There is no reason to define what objects you need up front. Simply load an object and start calling on its related objects. This works in both directions for both parent and child relationships (indeed even self-referencing relations).

//Load all Customers
using (var context = new NorthwindEntities())
	var customerCollection = context.Customer.ToList();

	//Get the first Customer
	var customer = customerCollection.FirstOrDefault();

	//Write out the UserType

	//How many Packages does this Customer have?

	//The Customer's first Package's Customer
	//(pointer back same customer)

In the example above, you can walk the Customer relationship to its one UserType object. A Customer has many packages, so there is a PackageList not a Package property. You can then pull the first item from the Package list and find its one Customer, which is of course the same Customer you started with. The relations can be walked up and down the relation graph.
It is interesting to note that all objects are loaded into the same context container. You can make changes to any number of objects in this context as you walk the hierarchy and save with a call to one persist method that is performed on the database in one transaction. All objects will be updated together or fail together.

Last edited May 8, 2012 at 1:39 PM by codetools, version 3


No comments yet.