In this article I will explain with an example, how to update data in Database using Entity Framework Code First Approach in ASP.Net MVC.
Note: If you want to learn about updating data using Entity Framework Database First Approach, please refer my article Update Data in Database using Entity Framework Database First Approach.
 
 
Database
Following is the Customers Table generated using Entity Framework Code First Approach.
Note: If you want to learn about inserting data using Entity Framework Code First Approach, please refer my article Insert Data in Database using Entity Framework Code First Approach.
 
Generated Customers Table Schema
Update Data in Database using Entity Framework Code First Approach
 
Records in Customers Table
Update Data in Database using Entity Framework Code First Approach
 
 
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.
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)
    {
        base.OnModelCreating(ModelBuilder);
    }
}
 
 
Controller
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 Updating
Inside this Action method, the Customer Model object is received as parameter.
The CustomerId value of the received Customer Model object is used to reference the Customer record.
Once the record is referenced, the values of Name and Country are updated and the changes are updated into the Customers table.
Based on whether the reference of the Customer is found or not, an appropriate message is set in the ViewBag object.
Finally, the Customer Model object is returned back to the View.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult Index(Customer customer)
    {
        using (CustomerDBContext context = new CustomerDBContext())
        {
            Customer updatedCustomer = (from c in context.Customers
                                        where c.CustomerId == customer.CustomerId
                                        select c).FirstOrDefault();
 
            if (updatedCustomer != null)
            {
                updatedCustomer.Name = customer.Name;
                updatedCustomer.Country = customer.Country;
                context.SaveChanges();
                ViewBag.Message = "Customer record updated.";
            }
            else
            {
                ViewBag.Message = "Customer not found.";
            }
        }
 
        return View(customer);
    }
}
 
 
View
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 are three TextBoxes created for capturing values of CustomerId, Name and Country using the Html.TextBoxFor method.
There’s also a Submit Button at the end of the Form. When the Update button is clicked, the values of CustomerId, Name and Country are passed to the Action method inside the Controller.
Finally, the value of the ViewBag object is checked for NULL and if it is not NULL then the value of the ViewBag object is displayed using JavaScript Alert MessageBox.
@model EF_CodeFirst_Update_MVC.Models.Customer
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <table border="0" cellpadding="0" cellspacing="0">
            <tr>
                <td style="width: 60px">
                    Id<br />
                    @Html.TextBoxFor(m => m.CustomerId, new { style = "width:50px" })
                </td>
                <td style="width: 150px">
                    Name<br />
                    @Html.TextBoxFor(m => m.Name, new { style = "width:140px" })
                </td>
                <td style="width: 150px">
                    Country:<br />
                    @Html.TextBoxFor(m => m.Country, new { style = "width:140px" })
                </td>
                <td style="width: 200px">
                    <br />
                    <input type="submit" id="btnUpdate" value="Update" />
                </td>
            </tr>
        </table>
    }
    @if (ViewBag.Message != null)
    {
        <script type="text/javascript">
            window.onload = function () {
                alert("@ViewBag.Message");
            };
        </script>
    }
</body>
</html>
 
 
Screenshot
Update Data in Database using Entity Framework Code First Approach
 
 
Downloads