EF “code-first” makes it easy to take advantage of
primary-key/foreign-key relationships within the database, and expose
properties on our model classes that enable us to traverse between model
classes using them.
Above we exposed a “Category” property on our Product class,
and a “Products” property on our Category class. Accessing these
properties enables us to use the PK/FK relationship between the two tables to
retrieve back model instances. Notice how the properties themselves are
still “POCO” properties and do not require us to use any EF-specific collection
type to define them.
Association properties that are marked as “virtual” will by
default be lazy-loaded. What this means is that if you retrieve a Product
entity, its Category information will not be retrieved from the database until
you access its Category property (or unless you explicitly indicate that the
Category data should be retrieved when you write your LINQ query to retrieve
the Product object).
EF Context Class
Once we’ve created our “Product” and “Category” POCO
classes, we used EF “code first” to create a “context” class that we can use to
map our POCO model classes to/from tables within the database:
The “Northwind” class above is the context class we are
using to map our Product and Category classes to/from the database. It
derives from the DbContext base class provided by EF “code-first”, and exposes
two properties that correspond to tables within our database. For this
sample we are using the default “convention over configuration” based mapping
rules to define how the classes should map to/from the database.
We could alternatively override the “OnModelCreating” method
and specify custom mapping rules if we wanted the object model
of our model classes to look differently than our database schema. My previous blog EF “code first” post covers how to do
this.