Overview
TheCategory model provides product classification in the supermarket system. Each category can contain multiple products through a one-to-many relationship, enabling organized inventory management and product browsing.
Class Definition
Properties
Primary key and unique identifier for the category. Auto-generated by the database.
The category name displayed in navigation menus and product listings. Examples: “Fruits”, “Dairy”, “Beverages”, “Bakery”.
Optional detailed description of the category. Can be used for category pages or help text. Nullable to allow categories without descriptions.
Navigation property containing the collection of products belonging to this category. Initialized to
default! to satisfy non-nullable reference type requirements while allowing Entity Framework to populate it.Relationships
Products Relationship (One-to-Many)
Each category can have multiple products:- One Category → Many Products
- Product contains
CategoryIdforeign key - Category contains
Productscollection
Usage Examples
Creating a New Category
Creating Category with Products
Updating Category
Getting Categories with Product Counts
Deleting Category
Be careful when deleting categories. If products reference the category, you’ll need to handle the foreign key constraint.
Database Schema
When migrated to the database, the Category table has the following structure:| Column | Type | Nullable | Key |
|---|---|---|---|
| Id | int | No | Primary Key (Identity) |
| Name | nvarchar(MAX) | No | |
| Description | nvarchar(MAX) | Yes |
The
Products navigation property does not create a database column. It’s a virtual collection managed by Entity Framework through the foreign key in the Products table.Querying Patterns
Get All Categories
Get Category by Name
Get Categories with Available Products
Search Categories
Navigation Property Initialization
TheProducts property uses a specific initialization pattern:
ICollection<Product>?- Nullable collection type= default!- Null-forgiving operator telling the compiler this will be initialized by Entity Framework- Allows EF to manage the collection lifecycle
- Prevents null reference warnings while maintaining flexibility
Best Practices
- Unique Names: Ensure category names are unique to avoid confusion
- Description Usage: Provide descriptions for better user experience
- Eager Loading: Use
.Include(c => c.Products)when you need product data - Cascade Deletes: Configure cascade delete behavior in
OnModelCreatingif needed - Null Checks: Always check if
Productscollection is null or empty before iterating - Performance: Use projections instead of loading entire product collections when you only need counts or specific fields
Cascade Delete Configuration
To configure cascade delete behavior inSupermarketContext:
Related Models
- Product Model - Products belonging to categories
- Data Models Overview - Complete entity relationship diagram