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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Because the class and property names align exactly with the entity and property names,<br />

<strong>Entity</strong> <strong>Framework</strong> will be able to work out the mapping between the classes and the<br />

entities, but you’re not done yet.<br />

Since these classes cannot rely on the <strong>Entity</strong>Object to <strong>com</strong>municate back to an<br />

ObjectContext, or even know that there is such a thing as an ObjectContext, the<br />

context will need another way to manage these classes so that it can perform its job of<br />

executing queries, returning objects, persisting changes to the database, and so forth.<br />

Creating an ObjectContext Class to Deliver the POCOs<br />

The Contact and Address classes have no knowledge at all about the <strong>Entity</strong><br />

<strong>Framework</strong>. This is a good thing as it is the desired effect. However, we need to let the<br />

<strong>Entity</strong> <strong>Framework</strong> be aware of the classes.<br />

Recall that the default code generator not only created the entity classes, but also created<br />

a class that inherited from ObjectContext. We don’t have one of those yet. The next<br />

step is to create your own class that inherits from ObjectContext and let it know<br />

about your custom classes. Once you have done this, the ObjectContext will do its<br />

job of querying, materializing, and managing the custom classes.<br />

For the sake of this simple demo, I am having you put everything into a<br />

single project. This is not the proper way to architect this type of<br />

solution, but is a simpler way to be introduced to the basic concepts.<br />

We’ll separate things out properly in the next example.<br />

Create a new class called Entities and add the code in Example 13-3 which emulates<br />

what you’ve seen in previous ObjectContext classes.<br />

Example 13-3. An ObjectContext class that works with the Contact and Address classes<br />

using System;<br />

using System.Collections.Generic;<br />

using System.Linq;<br />

using System.Text;<br />

using System.Data.Objects;<br />

namespace Chapter13SimplePOCO<br />

{<br />

class Entities : ObjectContext<br />

{<br />

private ObjectSet _contacts;<br />

private ObjectSet _addresses;<br />

public Entities()<br />

: base("name=POCOEntities", "POCOEntities")<br />

{<br />

_contacts = CreateObjectSet();<br />

_addresses = CreateObjectSet();<br />

}<br />

public ObjectSet Contacts<br />

{<br />

get<br />

{<br />

return _contacts;

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

Saved successfully!

Ooh no, something went wrong!