When the Entity Framework was first introduced developers
could generate a model from an existing database. This is called Database
First development. Then the next round of enhancements to the Entity Framework
allowed the developer to create the model and then generate a database from the
model. This is called Model First development. With the release of Entity
Framework 4.1 developers can now develop their classes with all the properties
and then generate a database from the classes. This is called Code First
Development.
Code first works great if you are the type of developer that
thinks about the object model or business logic layer first. You can build all
your classes and test out functionality before building the data model. You
could consider using this type of approach at the beginning of a project when
changes are happening rapidly and you want to get up and running with a
prototype quickly.
This article will demonstrate how to use the new Code First
features in Entity Framework 4.1 to create a database. You must install Entity
Framework 4.1 for these features to work. You can download the setup file here.
The code for the sample can be found here.
The sample will create an Invoice class and a LineItem
class. From these two classes a database called Accounting will be generated
with two corresponding tables. The you'll be able to bind the records in the
table to a GridView control and also Add, Update, and Delete the records in the
database. Finally, the sample will show you how to modify a database if the
classes change.