We do not need to write any additional code, nor create any
XML files, nor use any tools in order to map our model classes to and from a
database. How, you might ask, is that possible?
By default, EF code-first supports a “convention over
configuration” approach that enables you to rely on common mapping conventions
instead of having to explicitly configure things. You can override these
conventions if you want to provide custom database mapping rules. But if
you instead just use the default conventions you’ll find that the amount of
code you have to write is really small, and the common 90% of scenarios “just
work” the way you’d expect them to without any extra code or configuration.
In our example above, our NerdDinners context class will by
default map its “Dinners” and “RSVPs” properties to “Dinners” and “RSVPs”
tables within a database. Each row within the Dinners table will map to
an instance of our “Dinner” class. Likewise, each row within the RSVPs
table will map to an instance of our “RSVP” class. Properties within the
“Dinner” and “RSVP” classes in turn map to columns within the respective
“Dinners” and “RSVPs” database tables.
Other default conventions supported by EF include the
ability to automatically identify primary-key and foreign keys based on common
naming patterns (for example: an ID or DinnerID property on the Dinner class
will be inferred as the primary key). EF also includes smart conventions
for wiring-up association relationships between models. The EF team has a
blog post that talks more about how the default set of conventions work here.