04.07.2013 Views

Programming Entity Framework - Cdn.oreilly.com

Programming Entity Framework - Cdn.oreilly.com

Programming Entity Framework - Cdn.oreilly.com

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

loading on navigation properties even if you do not set up the class to enable change<br />

tracking.<br />

There is one more rule for enabling lazy loading on the navigation properties. Navigation<br />

properties that point to collections must be an ICollection. The<br />

ObjectContext will take care of the rest of the work for you.<br />

Example 13-9 shows the Addresses navigation property of the Contact class as a<br />

virtual property.<br />

VB<br />

C#<br />

Example 13-9. Enabling POCO classes to use a proxy for lazy loading<br />

Public Overridable Property Addresses() As ICollection(Of Address)<br />

public virtual ICollection Addresses {get; set;}<br />

Example 13-10 displays a method you can add to your console app to check three things<br />

for you. First, it verifies that the context recognizes you have modified the contact using<br />

the ObjectStateManager. Next, it will automatically load the Addresses. Finally,<br />

it saves your changes to the POCO Contact back to the database.<br />

Example 13-10. Verifying change tracking<br />

private static void VerifyVirtualChangeTracking()<br />

{<br />

using (Entities context = new Entities())<br />

{<br />

var contact = context.Contacts.First();<br />

contact.LastName = "Zappos";<br />

contact.FirstName = "Zelly";<br />

int modifiedEntities = context.ObjectStateManager.<br />

GetObjectStateEntries(System.Data.<strong>Entity</strong>State.Modified).Count();<br />

ICollection addresses = contact.Addresses;<br />

//break to verify that modifiedEntities is 1 and that addresses is not null<br />

context.SaveChanges();<br />

}<br />

}<br />

You can put a breakpoint on the last line of code (context.SaveChanges(););<br />

when it breaks, you can check in the debugger to see what’s in modifiedEntities<br />

and addresses just before SaveChanges is called, as noted in the <strong>com</strong>ment.<br />

Exploring the Proxy Classes<br />

When debugging code that uses these new classes, it is eye-opening to take a closer look<br />

at the classes.<br />

Figure 13-2 shows the Contact that you queried and edited in Example 13-10.

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

Saved successfully!

Ooh no, something went wrong!