Sunday, August 24, 2014

Create First Model Using Code First Conventions

Code first leverages a programming pattern referred to as convention over configuration.

If you follow the conventions correctly then Entity Framework will create the models correctly without any additional information. But if you don't follow the convention then you need to provide additional information to Entity Framework to create the models.

Let's create a simple Student class as follows:
namespace CodeFirstIntroduction.Data.Models
{
    public class Student
    {
        public int Id { getset; }
        public string Name { getset; }
    }
}

Here the Student class contains two properties: Id and Name. Entity Framework Code First treats "Id" as the primary key of the Student table as per the convention.

The convention is: Any table which property name is "Id"(case insensitive) will be the primary key or any property with name "class name + Id"(case insensitive)e.g. StudentId will be the primary key. If no such convention found then it will throw an exception during runtime for missing primary key.

To start using Code First, we need to create a class which will inherit from DbContext. See the next example:


using System.Data.Entity;
 
namespace CodeFirstIntroduction.Data.Models
{
    public class EducationContext : DbContext
    {
        public DbSet<Student> Students { getset; }
    }
}

Here the EducationContext class is inherited from DbContext which contains a property Students which is of type DbSet<Student>. Like the DbContext, the DbSet is a wrapper around the ObjectSet

Let's use the EducationContext to add a student information to Students DbSet as follows:


        using (var context = new EducationContext())
           {
               context.Students.Add(new Student
               {
                   Name = "Dukhabandhu Sahoo"
               });
 
               context.SaveChanges();
           }

When first time the application runs and the above code is executed then Entity Framework creates a database for you even if there is no connection string mentioned. If you are using it in a Web Application then a file named CodeFirstIntroduction.Data.Models.EducationContext.mdf will be added to the App_Data folder. If you note the name is the fully qualified name including the namespace and class name. It creates two tables: _MigrationHistory and Students.

Students tables is created as we have created DbSet<Student> Students property inside the EducationContext class. The _MigrationHistory(previously it was named EdmMetadata table till EF 4.2) table is created by Entity Framework to keep track of the changes happened to the database. The following image displays the actual database and tables created by the EducationContext.