In this article I will explain with an example, how to use Entity Framework with Code First Approach in ASP.Net MVC.
Code First Approach means code is written first and through code Database and its Tables are created.
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.
 
 

Namespaces
You will need to import the following namespaces.
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
 
 
Model
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.
StaffId
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.
 
StaffName
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.
[Table("Staff")]
public class Staff
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int StaffId { get; set; }
 
    [Required]
    [StringLength(50)]
    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: Entity Framework Code First Approach example
 
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)
    {
        base.OnModelCreating(ModelBuilder);
    }
}
 
 
Controller
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.
            context.Staff.Add(staff);
 
            // Final changes saved in Database Table.
            context.SaveChanges();
        }
        return View();
    }
}
 
 
View
For this particular example it is not required and hence the View is left empty.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
    </div>
</body>
</html>
 
 
Screenshots
Generated Staff Table Schema
ASP.Net MVC: Entity Framework Code First Approach example
 
Inserted Record
ASP.Net MVC: Entity Framework Code First Approach example
 
 
Downloads