15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

elationships ❘ 875<br />

or one-to-many relationship with Customer <strong>and</strong> Order because the CustomerID with the Order table is<br />

defined as Nullable in the database schema.<br />

figure 31-6<br />

You access the customers <strong>and</strong> their orders with two iterations shown here. First the Customer objects are<br />

accessed, <strong>and</strong> the value of the CompanyName property is written to the console. Then all orders are accessed<br />

by using the Orders property of the Customer class. The related orders are lazy loaded to access the<br />

property because with the ObjectContext the ContextOptions.LazyLoadingEnabled property is<br />

set to true:<br />

using (var data = new NorthwindEntities())<br />

{<br />

foreach (Customer customer in data.Customers)<br />

{<br />

Console.WriteLine("{0}", customer.CompanyName);<br />

}<br />

}<br />

foreach (Order order in customer.Orders)<br />

{<br />

Console.WriteLine("\t{0} {1:d}", order.OrderID, order.OrderDate);<br />

}<br />

code snippet NorthwindDemo/Program.cs<br />

Behind the scenes, the RelationshipManager class is used to access the relationship. The<br />

RelationShipManager instance can be accessed by casting the entity object to the interface<br />

IEntityWithRelationships as you can see in the designer-generated property Orders from the class<br />

Customer. This interface is explicitly implemented by the class EntityObject. The RelationshipManager<br />

property returns a RelationshipManager that is associated with the entity object at one end. The other<br />

end is defined by invoking the method GetRelatedCollection(). The first parameter NorthwindModel.<br />

FK_Orders_Customers is the name of the relationship: the second parameter Orders defines the name of<br />

the target role:<br />

public EntityCollection Orders<br />

{<br />

get<br />

{<br />

return ((IEntityWithRelationships)this).RelationshipManager.<br />

GetRelatedCollection("NorthwindModel.FK_Orders_Customers",<br />

"Orders");<br />

}<br />

set<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!