Code First with Entity Framework

Dheeraj Kumar Gunti

Reading Time : ( words)

Code First allows you to define your model using C# or VB.Net classes, optionally additional configuration can be performed using attributes on your classes and properties or by using a Fluent API. Your model can be used to generate a database schema or to map to an existing database.

  • Develop without ever having to open a designer or define an XML mapping file
  • Define your model objects by simply writing “plain old classes” with no base classes required
  • Use a “convention over configuration” approach that enables database persistence without explicitly configuring anything
  • Optionally override the convention-based persistence and use a fluent code API to fully customize the persistence mapping
Creating Context:

The simplest way to start using the classes for data access is to define a context that derives from System.Data.Entity.DbContext and exposes a typed DbSet for each class in my model. DbSet Class Represents an entity set that is used to perform create, read, update, and delete operations. DbSet and DbContext can be inherited from the namespace Microsoft.Data.Entity.CTP You can download ADO.NET Entity Framework Community Technology Preview (CTP) 4 here

Model builder is used to map CLR class to a db schema. This code centric approach to building an Entity Data Model (EDM) model is known as Code First. IncludeMetadataInDatabase is a property which is of bool type. Whenever dbcontext object is created automatically a db is created with respect to the clr classes, this includes even EDM meta data table which tracks the model changes. If we specify IncludeMetadataInDatabase property as false then it won't track the model changes. Model Builder class has one more pluggable component which manages the pluralization of entity classes.

Person Initializer class is created if user wants to create any predefined data for the person table. CreateDatabaseOnlyIfNotExists class can be used for creating database if it doesn't exists in disk. In Global.asax we need to initialize the PersonInitializer class to create predefined data.

When ever the context object is created automatically based on model compact database will be created with respect to the CLR class created (person). When the object is initialized it verifies the context name with connection settings in web.config with respect to that connection a compact database will be created in the local disk.