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.
Namespaces
You will need to import the following namespaces.
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
Model
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.
CustomerId
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.
[Table("Customers")]
public class Customer
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CustomerId { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
[Required]
[StringLength(50)]
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.
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)
{
base.OnModelCreating(ModelBuilder);
}
}
Controller
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" });
context.SaveChanges();
}
return View(context.Customers.ToList());
}
}
}
View
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>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<table cellpadding="0" cellspacing="0">
<tr>
<th>CustomerId</th>
<th>Name</th>
<th>Country</th>
</tr>
@foreach (Customer customer in Model)
{
<tr>
<td>@customer.CustomerId</td>
<td>@customer.Name</td>
<td>@customer.Country</td>
</tr>
}
</table>
</body>
</html>
Screenshots
Generated Customers Table Schema
Inserted Records in Customers Table
Displaying Records in HTML Table
Downloads