Skip to main content

Overview

The SupermarketContext class is the core Entity Framework Core database context for SupermarketWEB. It inherits from DbContext and provides access to all database entities through strongly-typed DbSet properties.
SupermarketContext is configured to work with SQL Server and is automatically injected into pages via dependency injection.

Class Definition

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; }
}
Location: Data/SupermarketContext.cs:7

Constructor

options
DbContextOptions
required
Configuration options for the database context, including the connection string and provider settings. This is typically configured in Program.cs using UseSqlServer().

DbSet Properties

The context exposes five main entity collections:
Products
DbSet<Product>
Collection for managing product records. Products include information about items sold in the supermarket.
Categories
DbSet<Category>
Collection for managing product categories. Categories can have multiple products through a navigation property.
Customers
DbSet<Customer>
Collection for managing customer information and records.
PayModes
DbSet<PayMode>
Collection for managing payment methods available in the system.
Users
DbSet<User>
Collection for managing user accounts with authentication credentials.

Configuration

The SupermarketContext is configured in Program.cs using the SQL Server provider:
builder.Services.AddDbContext<SupermarketContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("SupermarketDB"))
);
Connection String: The database connection is configured in appsettings.json under the key "SupermarketDB".

Dependency Injection

SupermarketContext is injected into PageModel constructors throughout the application:
public class IndexModel : PageModel
{
    private readonly SupermarketContext _context;

    public IndexModel(SupermarketContext context) 
    {
        _context = context;
    }

    public IList<Category> Categories { get; set; } = default!;

    public async Task OnGetAsync() 
    {
        if (_context.Categories != null) 
        {
            Categories = await _context.Categories.ToListAsync();
        }
    }
}

Common Operations

Querying Data

Use Entity Framework’s LINQ methods to query data:
// Get all categories
var categories = await _context.Categories.ToListAsync();

// Find by ID
var category = await _context.Categories
    .FirstOrDefaultAsync(c => c.Id == id);

// Query with conditions
var user = await _context.Users
    .FirstOrDefaultAsync(u => u.Email == email && u.Password == password);

Adding Records

_context.Categories.Add(Category);
await _context.SaveChangesAsync();

Updating Records

_context.Attach(Products).State = EntityState.Modified;
await _context.SaveChangesAsync();

Checking Existence

private bool ProductExists(int id)
{
    return (_context.Products?.Any(e => e.Id == id)).GetValueOrDefault();
}

Best Practices

Always check if the DbSet is not null before performing operations, especially when reading data.
  1. Use async operations: All database operations should use async/await pattern
  2. Call SaveChangesAsync(): Changes are not persisted until SaveChangesAsync() is called
  3. Handle exceptions: Wrap database operations in try-catch blocks for concurrency issues
  4. Dispose properly: The framework automatically handles disposal when using dependency injection

Build docs developers (and LLMs) love