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.

Example 13-6. The Contact.AddAddress method to fix up a two-way relationship<br />

public void AddAddress(Address address)<br />

{<br />

//instantiate Addresses if necessary<br />

if (Addresses == null)<br />

{<br />

Addresses=new List();<br />

}<br />

//add the address if it is not already in the list<br />

if (!Addresses.Contains(address))<br />

{<br />

Addresses.Add(address);<br />

}<br />

//set the contact property, but protect from circular reference<br />

if (address.Contact != this)<br />

{<br />

address.Contact = this;<br />

}<br />

}<br />

Next, you can modify the Address class so that it will also provide two-way<br />

relationship fix-ups.<br />

The current Contact property of the Address class uses an auto-implementer.<br />

Replace that with the code in Example 13-7.<br />

Example 13-7. The modified Address.Contact property to fix up the two-way relationship<br />

private Contact _contact;<br />

public Contact Contact<br />

{<br />

get { return _contact;}<br />

set {<br />

_contact = value;<br />

//explicit relationship fixup<br />

_contact.AddAddress(this);<br />

}<br />

}<br />

Notice that the property provides the alternate relationship by calling the AddAddress<br />

method of the contact. This is why the AddAddress method checks the value of the<br />

Address.Contact prior to setting the value; otherwise, you will trigger an infinite<br />

loop.<br />

Now, back in the Main method, <strong>com</strong>ment out the call to DetectChanges that you<br />

added earlier, and run the application again. You’ll see that the newAddressContact<br />

does get populated.<br />

Finally, you can check the other direction of the relationship. Replace the line of code<br />

that reads firstContact.Addresses.Add(newAddress); again, this time with<br />

newAddress.Contact=firstContact;. Now you are only setting the contact<br />

property of addresses. The address class will provide the fix-up for the other direction.<br />

You should find that this has caused the firstContact.Addresses.Count() to<br />

increase.

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

Saved successfully!

Ooh no, something went wrong!