Update Data to Database with Entity Framework in ASP.NET Core MVC


Create a database named LearnASPNETCoreMVCWithRealApps. This database have a table: Product table as below:

USE LearnASPNETMVCWithRealApps

/* Table structure for table `product` */

GO
CREATE TABLE Product (
    Id int IDENTITY(1,1) NOT NULL PRIMARY KEY,
	Name varchar(250) NULL,
	Price money NULL,
	Quantity int NULL,
	Status bit NOT NULL
)

/* Dumping data for table `product` */
GO
INSERT Product(Name, Price, Quantity, Status) VALUES('Name 1', 20.0000, 4, 1)
GO
INSERT Product(Name, Price, Quantity, Status) VALUES('Name 2', 12.0000, 8, 0)
GO
INSERT Product(Name, Price, Quantity, Status) VALUES('Name 3', 4.0000, 3, 1)
GO
INSERT Product(Name, Price, Quantity, Status) VALUES('Name 4', 17.0000, 8, 1)




On the Visual Studio, create new ASP.NET Core MVC Web Application project

Select Empty Template

Click Ok button to Finish

Open Startup.cs file and add new configurations as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace LearnASPNETCoreMVCWithRealApps
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Demo}/{action=Index}/{id?}");
            });

        }
    }
}

Select Project and right click to select Add\New Item Menu

Select Web\ASP.NET in left side. Select App Settings File item and click Add button to Finish

In appsettings.json file and new configurations as below:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=LearnASPNETCoreMVCWithRealApps;user id=sa;password=123456"
  }
}




Create new folder named Models. In Models folder, create new entity class as below:

Create new class named Product.cs as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LearnASPNETCoreMVCWithRealApps.Models
{
    public class Product
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public decimal Price { get; set; }

        public int Quantity { get; set; }

        public bool Status { get; set; }
    }
}

In Models folder, create new class named DataContext.cs, this file use Entity Framework to interact with the database as below:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace LearnASPNETCoreMVCWithRealApps.Models
{
    public class DataContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var builder = new ConfigurationBuilder()
                                    .SetBasePath(Directory.GetCurrentDirectory())
                                    .AddJsonFile("appsettings.json");
            var configuration = builder.Build();
            optionsBuilder.UseSqlServer(configuration["ConnectionStrings:DefaultConnection"]);
        }

        public DbSet<Product> Product { get; set; }

    }
}

Create new folder named Controllers. In Controllers folder, create new controller named ProductController.cs as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LearnASPNETCoreMVCWithRealApps.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace LearnASPNETCoreMVCWithRealApps.Controllers
{
    [Route("product")]
    public class ProductController : Controller
    {
        private DataContext db = new DataContext();

        [Route("")]
        [Route("index")]
        [Route("~/")]
        public IActionResult Index()
        {
            ViewBag.products = db.Product.ToList();
            return View();
        }

        [Route("edit")]
        [HttpGet]
        public IActionResult Edit()
        {
            return View("Edit");
        }

        [Route("edit")]
        [HttpPost]
        public IActionResult Edit(Product product)
        {
            db.Entry(product).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

    }
}




In Views/Product folder, create new razor views as below:

Create new view named Index.cshtml as below:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>

    <h3>Product List</h3>
    <table border="1">
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Price</th>
            <th>Quantity</th>
            <th>Status</th>
        </tr>
        @foreach (var product in ViewBag.products)
        {
            <tr>
                <td>@product.Id</td>
                <td>@product.Name</td>
                <td>@product.Price</td>
                <td>@product.Quantity</td>
                <td>@product.Status</td>
            </tr>
        }
    </table>

</body>
</html>

Create new view named Edit.cshtml as below:

@{
    Layout = null;
}

@model LearnASPNETCoreMVCWithRealApps.Models.Product

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Edit</title>
</head>
<body>

    <h3>Product Info</h3>
    <form method="post" asp-controller="product" asp-action="edit">
        <table cellpadding="2" cellspacing="2">
            <tr>
                <td>Id</td>
                <td>
                    <input type="text" asp-for="Id" />
                </td>
            </tr>
            <tr>
                <td>Name</td>
                <td>
                    <input type="text" asp-for="Name" />
                </td>
            </tr>
            <tr>
                <td>Price</td>
                <td>
                    <input type="text" asp-for="Price" />
                </td>
            </tr>
            <tr>
                <td>Quantity</td>
                <td>
                    <input type="text" asp-for="Quantity" />
                </td>
            </tr>
            <tr>
                <td>Status</td>
                <td>
                    <input type="checkbox" asp-for="Status" />
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <input type="submit" value="Save" />
                </td>
            </tr>
        </table>
    </form>

</body>
</html>




Access Index action in Product controller with following url: http://localhost:9596/product/edit

Output

Click Save button to update product to database

Output

I recommend you refer to the books below to learn more about the knowledge in this article: