Relational tables within a database are often structured
differently than how you want to design your object-oriented model classes.
What might be persisted as one large table within a database is sometimes best
expressed across multiple related classes from a pure object-oriented
perspective – and often you want the ability to split or shred tables across
multiple objects related to a single entity.
For example, instead of a single “colAddr” column for our
address, let’s assume our “tblDinners” database table uses multiple columns to
represent the “address” of our event:

Rather than surface these address columns as 4 separate
properties on our “Dinner” model class, we might instead want to encapsulate
them within an “Address” class and have our “Dinner” class exposes it as a property
like so:

Notice above how we’ve simply defined an “Address” class
that has 4 public properties, and the “Dinner” class references it simply by
exposing a public “Address” property. Our model classes are pure POCO
with no persistence knowledge.
We can update our “OnModelCreating” method to support a
mapping of this hierarchical class structure to a single table in the database
using a rule like so:

Notice how we are using the same mapping approach we used in
the previous example – where we map table column names to strongly-typed
properties on our model object. We are simply extending this approach to
support complex sub-properties as well. The only new concept above is
that we are also calling modelBuilder.ComplexType<Address>() to register
our Address as a type that we can use within mapping expressions.
And that is all we have to write to enable table shredding
across multiple objects.
Download an Updated NerdDinner Sample with Custom Database
Persistence Rules
You can download an updated version of the NerdDinner sample
here. It requires VS 2010 (or the free Visual Web
Developer 2010 Express).
You must download
and install SQL CE 4 on your machine for the above sample to work.
You can download the EF Code-First library here.
Neither of these downloads will impact your machine.