In this article I will explain with an example, how to insert record in Database using Entity Framework Code First Approach in ASP.Net MVC.
When the Form is submitted, the value of the submitted Form fields will be fetched and inserted into database using Entity Framework Code First Approach.
Note: If you want to learn about inserting data using Entity Framework Database First Approach, please refer my article Insert Data in Database using Entity Framework Database First Approach.
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 the following two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation for Inserting
Inside this Action method, the Customer Model object is received as parameter.
The received values are then inserted into the database table using Entity Framework Code First Approach.
The CustomerId of the inserted record is available in the Customer Model object after the SaveChanges method is executed.
Finally, the Customer Model object is returned back to the View.
public class HomeController : Controller
    // GET: Home
    public ActionResult Index()
        return View();
    public ActionResult Index(Customer customer)
        using (CustomerDBContext context = new CustomerDBContext())
            int id = customer.CustomerId;
        return View(customer);
Inside the View, in the very first line the Customer Model class is declared as Model for the View.
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionNameName of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
There is one TextBox field created for capturing value for Name using the Html.TextBoxFor method, while for capturing the Country value, a DropDownList with Country options is created using the Html.DropDownListFor function.
There’s also a Submit Button at the end of the Form and when the Button is clicked, the Form is submitted.
After the Form is submitted, the Customer Model returned from the Controller is checked for NULL and if it is not NULL then the newly inserted CustomerId is displayed using JavaScript Alert MessageBox.
@model EF_CodeFirst_Insert_MVC.Models.Customer
    Layout = null;
<!DOCTYPE html>
    <meta name="viewport" content="width=device-width" />
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
        <table cellpadding="0" cellspacing="0">
                <th colspan="2" align="center">Customer Details</th>
                <td>Name: </td>
                    @Html.TextBoxFor(m => m.Name)
                <td>Country: </td>
                    @Html.DropDownListFor(m => m.Country, new List<SelectListItem>
                   { new SelectListItem{Text="India", Value="India"},
                     new SelectListItem{Text="China", Value="China"},
                     new SelectListItem{Text="Australia", Value="Australia"},
                     new SelectListItem{Text="France", Value="France"},
                     new SelectListItem{Text="Unites States", Value="Unites States"},
                     new SelectListItem{Text="Russia", Value="Russia"},
                     new SelectListItem{Text="Canada", Value="Canada"}},
                     "Please select")
                <td><input type="submit" value="Submit" /></td>
    <script type="text/javascript" src=""></script>
    @if (Model != null)
        <script type="text/javascript">
            $(function () {
                alert("Inserted Customer ID: " + @Model.CustomerId);
Generated Customers Table Schema
Insert Data in Database using Entity Framework Code First Approach
The Form
Insert Data in Database using Entity Framework Code First Approach
CustomerId displayed after data insert
Insert Data in Database using Entity Framework Code First Approach
Inserted Record in Customers Table
Insert Data in Database using Entity Framework Code First Approach