How To Build an E-Commerce Application with ASP.NET 7 MVC and MSSQL Database? – Part 1

How To Build an E-Commerce Application with ASP.NET 7 MVC and MSSQL Database? – Part 1

This is the upgraded version in ASP.NET 7 of my earlier post here with ASP.NET 5. In the previous blog, I have shown the creation of the E-Commerce application using a generic list collection as data source. In this part, we shall create an e-commerce product shopping cart application with real MSSQL (local db) database. As per this article

“Microsoft SQL Server Express LocalDB is a feature of SQL Server Express targeted to developers. It is available on SQL Server Express with Advanced Services.

LocalDB installation copies a minimal set of files necessary to start the SQL Server Database Engine. Once LocalDB is installed, you can initiate a connection using a special connection string. When connecting, the necessary SQL Server infrastructure is automatically created and started, enabling the application to use the database without complex configuration tasks.” 

Here, I shall be creating the project step by step with code from absolute scratch using Visual Studio Community 2022 which can be downloaded from here. Please follow along till the end for more information and the source code for this part.

NOTE: The completed product cart with products, price, quantities and total cart cost and multiple other features is available in Part2

Create a New ASP.NET Core Project

Open up Visual Studio 2022 (Community version) and Click Create a new project as below (Fig. 1):

Fig 1

When Create a new project window opens (Fig 2) highlight ASP.NET Core Web App (Model-View-Controller) template and click Next( or simply double click ASP.NET Core Web App (Model-View-Controller) as below

Fig 2

On the Configure your new project window, give a suitable Project Name and Location and keep the checkbox marked Place solution and project in rhe same directory unchecked (Fig 3). Click Next

Fig 3

On the Additional information window select .NET 7.0 as Framework and other details as below (Fig 4) and hit Create

Fig 4

When the project is loaded, bring up the Solution Explorer window on the right hand. Expand the Controllers folder and highlight the default HomeController and delete it.

Now Go to the folder Views => Home and delete the Home folder (as it is no more required since we have already removed the HomeController)

Create a Product Model

Now to create a Product model, right click the default Models folder and add a Product class in a new file

Replace the default code in the Product class with the following:

namespace ECommerceShoppingCartAppASPNET7.Models
{
    public class Product
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
        public string Photo { get; set; }
    }
}

EF Core NuGet packages

This tutorial uses SQL Server, and the provider package is Microsoft.EntityFrameworkCore.SqlServer.

The EF SQL Server package and its dependencies, Microsoft.EntityFrameworkCore and Microsoft.EntityFrameoworkCore.Relational provide runtime support for Entity Framework. We now install the Nuget Packages Microsoft.EntityFrameworkCore.SqlServer.

We also add the Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore NuGet package. There are several ways that Nuget packages can be added. We use the Package Manager Console and issue the commands:

Install-Package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.SqlServer

The  Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore  NuGet package provides ASP.NET Core middleware for EF Core error pages. This middleware helps to detect and diagnose errors with EF Core migrations.

Create the database context

The main class that coordinates EF functionality for a given data model is the DbContext database context class. This class is created by deriving from the Microsoft.EntityFrameworkCore.DbContext class. The DbContext derived class specifies which entities are included in the data model. One can customize some EF behaviors. In this project, the name of the class is ProductContext.

In the project folder, create a folder named Data. To the Data folder, add a ProductContext.cs file and copy over the ProductContext class with the following code

using ECommerceShoppingCartAppASPNET7.Models;
using Microsoft.EntityFrameworkCore;
namespace ECommerceShoppingCartAppASPNET7.Data
{
    public class ProductContext : DbContext
    {
        public ProductContext(DbContextOptions<ProductContext> options):base(options) 
        { 
        }
        public DbSet<Product> Products { get; set;}
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Product>().ToTable("Product");
        }
    }
}

The preceding code creates a DbSet property for Product entity. In EF terminology:

  • An entity set typically corresponds to a database table. (Here it corresponds to the Product table)
  • An entity corresponds to a row in the table (Here the entity is a row on the Product table)

When we create the database, EF creates tables that have names the same as the DbSet property names. Property names for collections are typically plural. For example, Products rather than Product. For these tutorials, we override the default behavior by specifying singular table names in the DbContext. We achieve this in the preceding code in OnModelCreating method by the use of ToTable method

Register the ProductContext

ASP.NET Core includes dependency injection. We can register services such as EF database context, with dependency injection during start up. We can provide these services to the components (like MVC Controllers) that require them via constructor parameters. To register ProductContext as a service, we now edit the Program.cs so that it looks like the following:

using ECommerceShoppingCartAppASPNET7.Data;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<ProductContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
builder.Services.AddDbContext<ProductContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

In the Program Class we added the above snippet where name of the connection string is passed in to the context by calling a method on a DbContextOptionsBuilder object. For local development, the ASP.NET Core configuration system reads the connection string from the appsettings.json file.

Open the appsettings.json file and add a connection string as shown in the following markup above the Logging block (that is created by default when the Project is created) :

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=ECommerceProductDb;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Add the database exception filter

Add AddDatabaseDeveloperPageExceptionFilter to the services collection in the Program class as per the last line of the following code:

builder.Services.AddDbContext<ProductContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

SQL Server Express LocalDB

The connection string specifies SQL Server LocalDB. LocalDB is a lightweight version of the SQL Server Express Database Engine. We should use LocalDB for app development, and not for production. LocalDB starts on demand and runs in user mode, so there’s no complex configuration. By default, LocalDB creates .mdf DB files in the C:/Users/<user> directory.

Add Images to display in the cart

Next we create an images folder within the wwwroot folder and paste a few products. In this case, we display a variety of flowers for selling through the product cart, in line with the Product cart which we created earlier with ASP.NET 5 in the previous version of the blog (see Fig 5 below)

Fig 5

Initialize DB with test data

Entity Framework creates an empty database, automatically, with the EnsureCreated method in this tutorial. To see how, let’s create a new class named DbInitializer with the code below:

using ECommerceShoppingCartAppASPNET7.Models;
using System;
using System.Linq;

namespace ECommerceShoppingCartAppASPNET7.Data
{
    public static class DbInitializer
    {
        public static void Initialize(ProductContext context)
        {
            context.Database.EnsureCreated();
            //Look for any products
            if (context.Products.Any())
            {
                return;//DB has been seeded
            }
            var products = new Product[]
            {
                  new Product()
                  {
                      Id = "1",
                     Name = "Aconitum",
                      Photo = "Aconitum.jpg",
                      Price = 2.80
                  },

                new Product()
                {
                    Id="2",
                    Name = "African Daisy",
                    Photo = "AfricanDaisy.jpg",
                    Price = 3.80
                },
                new Product()
                {
                    Id="3",
                    Name = "Begonia",
                    Photo = "Begonia.jpg",
                    Price = 3.80
                },
                  new Product()
                  {
                      Id="4",
                      Name = "Chrysanthemum",
                      Photo = "Chrysanthemum.jpg",
                      Price = 3.60
                  },
                new Product()
                {
                    Id="5",
                    Name = "Dahlia",
                    Photo = "Dahlia.jpg",
                    Price = 6.80
                },
                new Product()
                {
                    Id="6",
                    Name = "Daisy",
                    Photo = "Daisy.jpg",
                    Price = 1.68
                },
                  new Product()
                  {
                      Id="7",
                      Name = "Echinacea",
                      Photo = "Echinacea.jpg",
                      Price = 3.80
                  },
                  new Product()
                  {
                      Id="8",
                      Name = "ForgetMeNot",
                      Photo = "ForgetMeNot.jpg",
                      Price = 3.45
                  },
                new Product()
                {
                    Id = "9",
                    Name = "Jasmine",
                    Photo = "Jasmine.jpg",
                    Price = 3.80
                }
                  
            };
            foreach (Product p in products)
            {
                context.Products.Add(p);
            }
            context.SaveChanges();

        }
    }
}

The preceding code checks if the database exists:

  • If the code does not find the database ;
    • It creates the database which is loaded with test data. It loads test data into arrays rather than List<T> collections to optimize performance.
  • If it finds the database, it takes no action.

Update Program.cs with the following code:

using ECommerceShoppingCartAppASPNET7.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;


var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
//builder.Services.AddMvc();
builder.Services.AddDbContext<ProductContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;
    try
    {
        var context = services.GetRequiredService<ProductContext>();
        DbInitializer.Initialize(context);
    }
    catch(Exception ex)
    {
        var logger = services.GetRequiredService<ILogger<Program>>();
        logger.LogError(ex, "An Error Occured Creating the DB");
    }
}

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Program.cs does the following on app startup (as we can see in the yellow highlighted code block):

  • Get a database context instance from the dependency injection container.
  • Call the DbInitializer.Initialize method.
  • Dispose the context when the Initialize method completes as shown in the following code:

The first time the app is run, the code creates the database and loads it with test data. Whenever the data model changes:

  • Delete the database.
  • Update the seed method, and start afresh with a new database.

Create controller and views

Now we shall create a Product Controller with the scaffolding engine in Visual Studio. Accordingly we shall right-click the Controllers folder and select Add Controller. On the Add New Scaffolded Item, select MVC Controller with views, using Entity Framework. Click Add (Fig 6)

Fig 6

On the Add MVC Controller with views, using Entity Framework dialog, select as in the screenshot (Fig 7) and click Add

Fig 7

As we see above,

  • In the Model class, we select Product
  • In the Data context class, select ProductContext
  • The default controller, we accept Products Controller as the name
  • Click Add

We notice that the controller takes a ProductContext as a constructor parameter. ASP.NET core dependency injection injects ProductContext as a dependency. We have configured that in the Program class.

namespace ECommerceShoppingCartAppASPNET7.Controllers
{
    public class ProductsController : Controller
    {
        private readonly ProductContext _context;

        public ProductsController(ProductContext context)
        {
            _context = context;
        }

The Visual Studio scaffolding engine also creates a set of views (*.cshtml files) that work with the controller. However, since it is an e-commerce (not a full-blown CRUD application), we only need the product listing. So we keep only the Index action method that gets the list of all the products as in the code block below and delete all other action methods that are not needed here.

// GET: Products
        public async Task<IActionResult> Index()
        {
              return _context.Products != null ? 
                          View(await _context.Products.ToListAsync()) :
                          Problem("Entity set 'ProductContext.Products'  is null.");
        }

In the code above, the return value is the products, which is asynchronously obtained, if the product context is not null. If the product context is null, on the other hand, then an appropriate message is sent as response.

Open the Views/Products/Index.cshtml file and write the following code to replace the scaffolding engine generated code :

@model IEnumerable<ECommerceShoppingCartAppASPNET7.Models.Product>

@{
    ViewData["Title"] = "Index";
}

<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h3>Products List</h3>
    <table class="table">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Id)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Price)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Photo)
                </th>
                <th></th>
            </tr>
        </thead>
        @foreach (var product in Model)
        {
            <tr>
                <td>@product.Id</td>
                <td>@product.Name</td>
                <td>@(Math.Round(product.Price, 2))</td>
                <td><img src="~/images/@product.Photo" width="60" /> </td>

                <td align="center">
                    <button class="add-to-cart" data-product-id="@product.Id">
                        Add to Cart
                    </button>
                </td>
            </tr>
        }
    </table>
</body>

Note: In the code above, Users can select the desired item and click the “Add to Cart” button to add the products to the cart without navigating away from the product list. However the complete functionality is avaiable in Part2

Running the application

To run the application, press Ctrl + F5 (Start without debugging) light green arrow on top. We get the following browser rendered (Fig 8):

That’s it in this part. Clicking any of these Add to Cart buttons doesn’t do anything as it has not yet been coded.

The completed product cart with products, price, quantities and total cart cost and multiple other features is available in Part2

Source Code

The complete source code for this part can be found here

Follow Me Here

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.