EF4 “Code First” enables you to optionally override its
default database persistence mapping rules, and configure alternative ways to
map your classes to a database.
There are a few ways to enable this. One of the
easiest approaches is to override the “OnModelCreating” method defined on the
DbContext base class:
The OnModelCreating method above will be called the first
time our NerdDinners class is used within a running application, and it is
passed a “ModelBuilder” object as an argument. The ModelBuilder object
can be used to customize the database persistence mapping rules of our model
objects. We’ll look at some examples of how to do this below.
EF only calls the “OnModelCreating” method once within a
running application – and then automatically caches the ModelBuilder
results. This avoids the performance hit of model creation each time a
NerdDinners class is instantiated, and means that you don’t have to write any
custom caching logic to get great performance within your applications.