Overview
TheSupermarketContext 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
Data/SupermarketContext.cs:7
Constructor
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:Collection for managing product records. Products include information about items sold in the supermarket.
Collection for managing product categories. Categories can have multiple products through a navigation property.
Collection for managing customer information and records.
Collection for managing payment methods available in the system.
Collection for managing user accounts with authentication credentials.
Configuration
The SupermarketContext is configured inProgram.cs using the SQL Server provider:
appsettings.json under the key "SupermarketDB".
Dependency Injection
SupermarketContext is injected into PageModel constructors throughout the application:Common Operations
Querying Data
Use Entity Framework’s LINQ methods to query data:Adding Records
Updating Records
Checking Existence
Best Practices
Always check if the DbSet is not null before performing operations, especially when reading data.
- Use async operations: All database operations should use async/await pattern
- Call SaveChangesAsync(): Changes are not persisted until
SaveChangesAsync()is called - Handle exceptions: Wrap database operations in try-catch blocks for concurrency issues
- Dispose properly: The framework automatically handles disposal when using dependency injection