In this article I will explain with an example, how to display data from Database using 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 Customer.
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 three properties.
The property CustomerId 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 value automatically when record inserted in the table.
Name and Country
The properties Name and Country are decorated with the following two 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 Customer
    public int CustomerId { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
Database Context
Following is the Database Context class, CustomerDBContext. The Connection String is fetched from the Web.Config file using the key.
Note: For more details about Database Context class, please refer my article ASP.Net MVC: Entity Framework Code First Approach example.
using System.Data.Entity;
public class CustomerDBContext : DbContext
    public CustomerDBContext() : base("name=constr")
        // The Database is initialized and created.
        Database.SetInitializer(new CreateDatabaseIfNotExists<CustomerDBContext>());
    // A DbSet for each Entity (Table) needs to be added.
    public DbSet<Customer> Customers { 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 following Action method.
Action method for handling GET operation
Inside this Action method, a check is performed whether records are present or not in the Customers table in Database.
If the Customers table is empty, then dummy records are inserted into the Customers collection of the CustomerDBContext using the Add method and the SaveChanges method is called which saves all changes made in the database table.
Finally, the records are fetched from the Customers table using Entity Framework Code First Approach and returned to the View.
public class HomeController : Controller
    // GET: Home
    public ActionResult Index()
        using (CustomerDBContext context = new CustomerDBContext())
            if (context.Customers.ToList().Count == 0)
                // Adding Dummy data.
                context.Customers.Add(new Customer() { Name = "John Hammond", Country = "United States" });
                context.Customers.Add(new Customer() { Name = "Mudassar Khan", Country = "India" });
                context.Customers.Add(new Customer() { Name = "Suzanne Mathews", Country = "France" });
                context.Customers.Add(new Customer() { Name = "Robert Schidner", Country = "Russia" });
            return View(context.Customers.ToList());
Inside the View, in the very first line the Customer Entity is declared as IEnumerable which specifies that it will be available as a Collection.
For displaying the records, an HTML Table is used. A loop will be executed over the Model which will generate the HTML Table rows with the Customer records.
@using EF_CodeFirst_Display_MVC.Models;
@model IEnumerable<Customer>
    Layout = null;
<!DOCTYPE html>
    <meta name="viewport" content="width=device-width" />
    <table cellpadding="0" cellspacing="0">
        @foreach (Customer customer in Model)
Generated Customers Table Schema
Entity Framework Code First Approach: Display Data from Database in ASP.Net MVC
Inserted Records in Customers Table
Entity Framework Code First Approach: Display Data from Database in ASP.Net MVC
Displaying Records in HTML Table
Entity Framework Code First Approach: Display Data from Database in ASP.Net MVC