In this article I will explain with an example, how to get started with Entity Framework Code First Approach in ASP.Net MVC.
Note: If you want to learn about Entity Framework Database First Approach, please refer my article ASP.Net MVC: Entity Framework Database First Approach example.
You will need to import the following namespaces.
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
Following is the Model class Staff.
It is decorated with the Table Data Annotation. It is used to override the default Table name in the Database.
The Model class consists of two properties.
The property StaffId is decorated with the following two Data Annotation attributes:
Key – It is used to apply the Primary Key constraint to the Column.
DatabaseGenerated – It is used to make the column as an Identity column in the Table i.e. the column that generates its automatically when record inserted in the table.
The property StaffName is decorated with the following Data Annotation attributes:
Required – It sets the column as NOT NULL in the Table which means the column will not accept NULL values.
StringLength – It sets the value of the maximum number of characters allowed in the column. Basically, it is the length of the Field.
public class Staff
    public int StaffId { get; set; }
    public string StaffName { get; set; }
Database Context
You will need to add a new class to your project by Right clicking the Solution Explorer and then click on Add and then New Item option of the Context Menu.
ASP.Net MVC: Get Started with Entity Framework Code First Approach
Inside the class, first we will start by adding the System.Data.Entity namespace and then the DbContext class is inherited in the class.
Next, a Constructor is created and the Constructor will call the Constructor of the base class (DbContext class) and the name of the Connection String is passed as parameter to the Constructor.
Now, inside the Constructor, the SetInitializer method of Database class is called which will create the Database if it does not exists.
Then, based on how many Tables you need in the Database, you need to add DbSet properties. For example, here only one table Staff is needed and hence only property of type DbSet collection is created.
Finally, OnModelCreating method is overridden inside the DbContext class.This method is used to configure the model without modifying the entity classes.
using System.Data.Entity;
public class StaffDbContext : DbContext
    // Setting the Connection String.
    public StaffDbContext() : base("name=constr")
        // The Database is initialized and created.
        Database.SetInitializer(new CreateDatabaseIfNotExists<StaffDbContext>());
    // A DbSet for each Entity (Table) needs to be added.
    public DbSet<Staff> Staff { get; set; }
    // Add a DbSet for each entity type that you want to include in your model.
    protected override void OnModelCreating(DbModelBuilder ModelBuilder)
The controller consists of the following Action method.
Action method for handling GET operation
Inside this Action method, the StaffDbContext class is initialized and a Staff record is inserted.
When the Staff record is inserted, the Database and Table are created.
Finally, the SaveChanges method is called which saves all changes made in the context class and the View is returned.
public class HomeController : Controller
    // GET: Home
    public ActionResult Index()
        // Create StaffDbContextobject.
        using (StaffDbContext context = new StaffDbContext())
            //Create a Staff object.
            Staff staff = new Staff() { StaffName = "Mudassar Khan" };
            //Add Staff object to Context.
            // Final changes saved in Database Table.
        return View();
For this particular example it is not required and hence the View is left empty.
    Layout = null;
<!DOCTYPE html>
    <meta name="viewport" content="width=device-width" />
Generated Staff Table Schema
ASP.Net MVC: Get Started with Entity Framework Code First Approach
Inserted Record
ASP.Net MVC: Get Started with Entity Framework Code First Approach