Skip to main content
SupermarketWEB uses SQL Server LocalDB with Entity Framework Core 8.0 for data persistence. This guide covers database configuration, context setup, and initialization.

Prerequisites

1

SQL Server LocalDB

Install SQL Server LocalDB (included with Visual Studio) or SQL Server Express
2

Entity Framework Core Tools

Install EF Core tools globally:
dotnet tool install --global dotnet-ef

Connection String Configuration

The database connection is configured in appsettings.json:
appsettings.json
{
  "ConnectionStrings": {
    "SupermarketDB": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=SupermarketEF;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False"
  }
}
The connection string uses SQL Server LocalDB with integrated security, which authenticates using your Windows credentials. No separate username or password is required.

Connection String Parameters

ParameterValuePurpose
Data Source(localdb)\\MSSQLLocalDBLocalDB instance name
Initial CatalogSupermarketEFDatabase name
Integrated SecurityTrueUse Windows authentication
EncryptFalseDisable connection encryption for local development
For production environments, change the connection string to use a full SQL Server instance with proper encryption and authentication.

Entity Framework Core Configuration

DbContext Registration

The SupermarketContext is registered in Program.cs:
Program.cs
using Microsoft.EntityFrameworkCore;
using SupermarketWEB.Data;

var builder = WebApplication.CreateBuilder(args);

// Register DbContext with SQL Server provider
builder.Services.AddDbContext<SupermarketContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("SupermarketDB"))
);
This configuration:
  • Registers SupermarketContext in the dependency injection container
  • Configures the SQL Server provider
  • Reads the connection string from appsettings.json

DbContext Implementation

The SupermarketContext class in Data/SupermarketContext.cs defines all database tables:
Data/SupermarketContext.cs
using Microsoft.EntityFrameworkCore;
using SupermarketWEB.Models;

namespace SupermarketWEB.Data
{
    public class SupermarketContext : DbContext
    {
        public SupermarketContext(DbContextOptions options) : base(options)
        {
        }

        public DbSet<Product> Products { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Customer> Customers { get; set; }
        public DbSet<PayMode> PayModes { get; set; }
        public DbSet<User> Users { get; set; }
    }
}
Each DbSet<T> property represents a table in the database:
  • Products - Product inventory items
  • Categories - Product categories
  • Customers - Customer information
  • PayModes - Payment methods
  • Users - Application users for authentication

Database Initialization

1

Create Initial Migration

Generate the first migration to create database schema:
dotnet ef migrations add InitialCreate
This creates a migration file in the Migrations folder with the database schema definition.
2

Apply Migration to Database

Create the database and apply the migration:
dotnet ef database update
This command:
  • Creates the SupermarketEF database if it doesn’t exist
  • Applies all pending migrations
  • Creates tables for all DbSet properties
3

Verify Database Creation

Connect to LocalDB using SQL Server Object Explorer in Visual Studio or SQL Server Management Studio to verify the database and tables were created successfully.

Working with Migrations

Create a New Migration

After modifying model classes, create a new migration:
dotnet ef migrations add <MigrationName>
Use descriptive migration names like AddProductStockColumn or CreateCustomersTable to make the migration history clear.

Apply Migrations

Update the database with pending migrations:
dotnet ef database update

Rollback Migration

Revert to a specific migration:
dotnet ef database update <PreviousMigrationName>

Remove Last Migration

Remove the most recent unapplied migration:
dotnet ef migrations remove
Only remove migrations that haven’t been applied to production databases. Removing applied migrations can cause data loss.

Database Schema

The SupermarketWEB database includes the following entities:
  • Id (int, primary key)
  • Name (string)
  • Price (decimal(6,2))
  • Stock (int)
  • CategoryId (int, foreign key)
Relationships: Many-to-One with Category
  • Id (int, primary key)
  • Name (string)
  • Description (string, nullable)
Relationships: One-to-Many with Products
  • Id (int, primary key)
  • Customer-specific fields (see Models/Customer.cs)
  • Id (int, primary key)
  • Payment mode fields (see Models/PayMode.cs)
  • Id (int, primary key)
  • Authentication fields (see Models/User.cs)

Troubleshooting

LocalDB Instance Not Found

If you encounter connection errors, verify LocalDB is installed:
sqllocaldb info
Create a new LocalDB instance if needed:
sqllocaldb create MSSQLLocalDB
sqllocaldb start MSSQLLocalDB

Migration Errors

If migrations fail, check:
  • Ensure the database is not in use by other applications
  • Verify connection string credentials
  • Check migration files for conflicts
  • Review the error message for specific model or constraint issues

Connection Timeout

Increase the connection timeout in appsettings.json if needed:
"SupermarketDB": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=SupermarketEF;Integrated Security=True;Connect Timeout=60;..."

Next Steps

  • Learn about the Project Structure to understand how the application is organized
  • Explore Razor Pages to see how data is accessed and displayed

Build docs developers (and LLMs) love