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

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

USE LearnASPNETCoreMVC5WithRealApps

/* 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, select Create a new project from Get Started

Select ASP.NET Core Web Application




Input Project Name and select Location for new project

Select ASP.NET Core 5.0 Version and select ASP.NET Core Empty Template. Click Create button to finish




Use NuGet add Libraries need for Entity Framework Core as below:

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Tools
  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.SqlServer.Design
  • Microsoft.EntityFrameworkCore.Proxies
  • Microsoft.Extensions.Configuration.JSON

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

using LearnASPNETCoreMVC5.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace LearnASPNETCoreMVC5
{
    public class Startup
    {
        public IConfiguration configuration;

        public Startup(IConfiguration _configuration)
        {
            configuration = _configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            var connectionString = configuration.GetConnectionString("DefaultConnection");
            services.AddDbContext<DataContext>(options => options.UseLazyLoadingProxies().UseSqlServer(connectionString));
        }

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

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{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=LearnASPNETCoreMVC5WithRealApps;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.ComponentModel.DataAnnotations.Schema;

namespace LearnASPNETCoreMVC5.Models
{
    [Table("Product")]
    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 as below:

using Microsoft.EntityFrameworkCore;

namespace LearnASPNETCoreMVC5.Models
{
    public class DataContext : DbContext
    {
        public DataContext()
        {
        }

        public DataContext(DbContextOptions<DataContext> options)
            : base(options)
        {
        }

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

    }
}




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

using LearnASPNETCoreMVC5.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq;

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

        public ProductController(DataContext _db)
        {
            db = _db;
        }

        [Route("")]
        [Route("index")]
        [Route("~/")]
        public IActionResult Index()
        {
            ViewBag.products = db.Products.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 views as below:

Create new view named Index.cshtml as below:

<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:

@model LearnASPNETCoreMVC5.Models.Product

<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>




Select Views folder and right click to select Add\New Item Menu

Select Web\ASP.NET in left side. Select Razor View Imports item and click Add button to Finish

In _ViewImports.cshtml file and TagHelpers library as below:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers




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

Output

Click Save button to update product to database

Output