In this article I will explain with an example, how to populate (bind) WebGrid using Entity Framework Code First Approach in ASP.Net MVC.
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
    publicCustomerDBContext() : 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 Model is declared as IEnumerable which specifies that it will be available as a Collection.
For displaying the records, a WebGrid is used. The WebGrid is initialized with the Model i.e. IEnumerable collection of Customer Model class objects as source.
The WebGrid is created using the GetHtml method with the following parameters.
HtmlAttributes – It is used to set the HTML attributes to the HTML Table generated by WebGrid such as ID, Name, Class, etc.
Columns – It is used to specify the columns to be displayed in WebGrid and also allows to set specific Header Text for the columns.
Note: If the columns are not specified then WebGrid will display all columns supplied by its source. It is very similar to the AutoGenerateColumns feature of the ASP.Net GridView.
@model IEnumerable<WebGrid_EF_CodeFirst_MVC.Models.Customer>
    Layout = null;
    WebGrid webGrid = new WebGrid(source: Model, canPage: false, canSort: false);
<!DOCTYPE html>
    <meta name="viewport" content="width=device-width" />
        htmlAttributes: new { @id = "WebGrid", @class = "Grid" },
        columns: webGrid.Columns(
            webGrid.Column("CustomerId", "CustomerId"),
            webGrid.Column("Name", "Name"),
            webGrid.Column("Country", "Country")))
Generated Customers Table Schema
Populate (Bind) WebGrid using Entity Framework Code First Approach in ASP.Net MVC
Inserted Records in Customers Table
Populate (Bind) WebGrid using Entity Framework Code First Approach in ASP.Net MVC
The WebGrid displaying Customer records
Populate (Bind) WebGrid using Entity Framework Code First Approach in ASP.Net MVC