Overview
TheProduct model represents items in the supermarket inventory. It includes pricing information, stock levels, and a relationship to the Category model for product classification.
Class Definition
Properties
Primary key and unique identifier for the product. Auto-generated by the database.
The product name or title displayed to customers and used in inventory management.
Product price with precision of 6 digits total and 2 decimal places. Stored as
decimal(6,2) in the database, allowing values up to 9999.99.Column Attribute: [Column(TypeName = "decimal(6,2)")] ensures precise decimal storage without floating-point errors.Current inventory quantity available for sale. Used for stock management and availability checks.
Foreign key reference to the Category table. Establishes the many-to-one relationship between products and categories.
Navigation property to the related Category entity. Nullable to support lazy loading and optional eager loading scenarios.
Data Annotations
Column Type Specification
ThePrice property uses a column type annotation to ensure precise decimal handling:
The
decimal(6,2) type specification means:- 6: Total number of digits (precision)
- 2: Number of digits after decimal point (scale)
- Range: -9999.99 to 9999.99
float or double types, which is critical for financial calculations.
Relationships
Category Relationship (Many-to-One)
Each product belongs to exactly one category:Usage Examples
Creating a New Product
Updating Stock
Querying Products by Category
Low Stock Alert
Database Schema
When migrated to the database, the Product table has the following structure:| Column | Type | Nullable | Key |
|---|---|---|---|
| Id | int | No | Primary Key (Identity) |
| Name | nvarchar(MAX) | No | |
| Price | decimal(6,2) | No | |
| Stock | int | No | |
| CategoryId | int | No | Foreign Key → Categories.Id |
The
Category navigation property does not create a database column. It’s used by Entity Framework for relationship mapping.Best Practices
- Price Precision: Always use
decimaltype for currency to avoid rounding errors - Stock Validation: Implement business logic to prevent negative stock values
- Category Assignment: Ensure CategoryId references a valid Category before saving
- Eager Loading: Use
.Include()when you know you’ll need the Category to avoid N+1 queries - Null Checks: Always check if
Categoryis null before accessing its properties if not using eager loading
Related Models
- Category Model - Product categorization
- Data Models Overview - Complete entity relationship diagram