In this article I will explain with an example, how to update data in Database using Entity Framework Code First Approach in ASP.Net Core MVC.
Note: If you want to learn about inserting data using Entity Framework Code First Approach, please refer my article ASP.Net Core: Insert Data into Database using Entity Framework Code First Approach.
 
 
Database
Following is the Customers Table generated using Entity Framework Code First Approach.
Note: For more details, please refer my article ASP.Net Core MVC: EntiyFramework Code First Approach with Existing Database.
 
Generated Customers Table Schema
ASP.Net Core: Update Data in Database using Entity Framework Code First Approach
 
Records in Customers Table
ASP.Net Core: Update Data in Database using Entity Framework Code First Approach
 
 
Database Context
Following is the Table and Database Context classes.
Generated Table class
public partial class Customers
{
    [Key]
    public int CustomerId { get; set; }
 
    [Required]
    [StringLength(100)]
    public string Name { get; set; }
 
    [Required]
    [StringLength(50)]
    public string Country { get; set; }
}
 
Generated Database Context
public partial class CodeFirstContext : DbContext
{
    public CodeFirstContext()
    {
    }
 
    public CodeFirstContext(DbContextOptions<CodeFirstContext> options)
        : base(options)
    {
    }
 
    public virtual DbSet<Customers> Customers { get; set; }
 
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
            optionsBuilder.UseSqlServer("Data Source=.\\SQL2019;Initial Catalog=CodeFirst;Trusted_Connection=True;");
        }
    }
 
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customers>(entity =>
        {
            entity.Property(e => e.Country).IsUnicode(false);
 
            entity.Property(e => e.Name).IsUnicode(false);
        });
    }
}
 
 
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 class object is received as parameter.
The CustomerId value of the received Customer Model class 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 class object is returned back to the View.
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public IActionResult Index(Customers customer)
    {
        using (CodeFirstContext context = new CodeFirstContext())
        {
            Customers 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 Customers Model class is declared as Model for the View and the ASP.Net TagHelpers is inherited.
The View consists of an HTML Form which has been created using the ASP.Net TagHelpers attributes with the following attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – 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.
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_Core.Models.Customers
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <form method="post" asp-action="Index" asp-controller="Home">
        <table>
            <tr>
                <td style="width: 60px">
                    Id<br />
                    <input type="text" asp-for="CustomerId" style="width:50px" />
                </td>
                <td style="width: 150px">
                    Name<br />
                    <input type="text" asp-for="Name" style="width:140px" />
                </td>
                <td style="width: 150px">
                    Country:<br />
                    <input type="text" asp-for="Country" style="width:140px" />
                </td>
                <td style="width: 200px">
                    <br />
                    <input type="submit" id="btnUpdate" value="Update" />
                </td>
            </tr>
        </table>
    </form>
    @if (ViewBag.Message != null)
    {
        <script type="text/javascript">
            window.onload = function () {
                alert("@ViewBag.Message");
            };
        </script>
    }
</body>
</html>
 
 
Screenshot
ASP.Net Core: Update Data in Database using Entity Framework Code First Approach
 
 
Downloads