Database Overview

The Shirinzad E-Commerce platform uses SQL Server 2019+ with Entity Framework Core 9.0 for database management. The schema consists of 58 tables organized into 9 modules with comprehensive indexing for optimal performance.

Technology Stack: SQL Server 2019+ | EF Core 9.0 | Code-First Migrations | 20+ Migrations Applied

Database Statistics

58
Total Tables
46+
Strategic Indexes
20+
Migrations
9
Module Groups

Entity Relationship Diagram (ERD)

Core E-Commerce Relationships

erDiagram Product ||--o{ ProductCategory : "has many" Product ||--o{ ProductTag : "has many" Product ||--o{ ProductVariant : "has many" Product ||--o{ ProductSpec : "has many" Product ||--o{ ProductGallery : "has many" Product ||--o{ ProductReview : "has many" Product ||--o{ CartItem : "in cart" Product ||--o{ OrderItem : "in order" Product ||--o{ WishlistItem : "in wishlist" Product }o--|| Brand : "belongs to" Category ||--o{ ProductCategory : "has many" Category ||--o{ Category : "parent-child" Tag ||--o{ ProductTag : "has many" Tag ||--o{ BlogPostTag : "has many" Cart ||--o{ CartItem : "contains" Cart }o--|| User : "belongs to" Order ||--o{ OrderItem : "contains" Order ||--o{ OrderStatusHistory : "has history" Order ||--o{ Payment : "has payments" Order ||--o{ Shipment : "has shipments" Order }o--|| User : "placed by" Shipment ||--o{ ShipmentItem : "contains" Shipment }o--|| ShippingMethod : "uses" Payment }o--|| PaymentMethod : "uses" Discount ||--o{ DiscountProduct : "applies to" Discount ||--o{ DiscountCategory : "applies to" ProductReview ||--o{ ReviewReply : "has replies" ProductReview ||--o{ ReviewLike : "has likes" ProductReview ||--o{ ReviewImage : "has images" User ||--o{ UserAddress : "has addresses" User ||--|| UserProfile : "has profile" User ||--o{ Wishlist : "has wishlists" User ||--o{ Notification : "receives"

Core relationships showing product catalog, orders, and user interactions

Automotive & Content Modules

erDiagram VehicleMake ||--o{ VehicleModel : "has models" VehicleModel ||--o{ Vehicle : "has vehicles" VehicleModel ||--o{ VehiclePartCompatibility : "compatible with" VehiclePart ||--o{ VehiclePartCompatibility : "compatible with" VehiclePart }o--|| PartCategory : "belongs to" PartCategory ||--o{ PartCategory : "parent-child" Service ||--o{ VehicleService : "applies to" Service }o--|| ServiceCategory : "belongs to" Vehicle ||--o{ VehicleService : "has services" BlogPost ||--o{ BlogPostTag : "has tags" BlogPost ||--o{ BlogComment : "has comments" BlogPost }o--|| BlogCategory : "belongs to" BlogComment ||--o{ BlogComment : "parent-child (replies)" Menu ||--o{ MenuItem : "contains" MenuItem ||--o{ MenuItem : "parent-child (submenu)"

Automotive parts, services, and content management relationships

Tables by Module

Catalog Module (19 Tables)

Product management, categories, brands, tags, reviews, wishlist, and comparison features.

Table Name Primary Key Description Key Indexes
Products Guid Id Main product entity with pricing, stock, ratings Slug (unique), Code, IsActive, IsFeatured, BrandId, CreationTime
Categories Guid Id Hierarchical product categories Slug (unique), IsActive, DisplayOrder, ParentId
Brands Guid Id Product brands/manufacturers Slug (unique), IsActive, DisplayOrder
Tags Guid Id Product tags for filtering and SEO Slug (unique), Name
ProductCategories ProductId, CategoryId Many-to-many: Products to Categories ProductId, CategoryId
ProductTags ProductId, TagId Many-to-many: Products to Tags ProductId, TagId
ProductVariants Guid Id Product variations (size, color, etc.) ProductId, Sku, IsActive, DisplayOrder
ProductSpecs Guid Id Technical specifications (key-value pairs) ProductId, (ProductId + Group), DisplayOrder
ProductGalleries Guid Id Product image gallery ProductId, DisplayOrder
ProductReviews Guid Id Customer reviews and ratings ProductId, UserId, Rating, IsApproved, IsFeatured, IsVerifiedPurchase, CreationTime
ReviewReplies Guid Id Replies to product reviews ProductReviewId, IsOfficial, CreationTime
ReviewLikes ProductReviewId, UserId, IpAddress Helpful/not helpful votes on reviews ProductReviewId, UserId, IsHelpful
ReviewImages Guid Id Images attached to reviews ProductReviewId, DisplayOrder
ProductQuestions Guid Id Customer questions about products ProductId, UserId, IsApproved, CreationTime
ProductAnswers Guid Id Answers to product questions QuestionId, UserId, IsApproved, IsSellerAnswer, CreationTime
Wishlists Guid Id Customer wishlists (can have multiple) UserId, (UserId + IsDefault), IsPublic, CreationTime
WishlistItems Guid Id Products in wishlists WishlistId, ProductId, (WishlistId + ProductId), Priority, CreationTime
ComparisonLists Guid Id Product comparison lists UserId, SessionId, CategoryId, ExpiresAt, CreationTime
ComparisonItems Guid Id Products in comparison lists ComparisonListId, ProductId, (ComparisonListId + ProductId), DisplayOrder

Orders Module (13 Tables)

Shopping cart, orders, payments, shipments, and discounts.

Table Name Primary Key Description Key Indexes
Carts Guid Id Shopping cart (guest or registered) UserId, SessionId, IsActive, ExpiresAt, CreationTime
CartItems Guid Id Items in shopping cart CartId, ProductId, VariantId, CreationTime
Orders Guid Id Customer orders with complete details OrderNumber (unique), UserId, Status, CustomerEmail, PaymentTransactionId, TrackingNumber, CreationTime
OrderItems Guid Id Line items in orders OrderId, ProductId, VariantId, CreationTime
OrderStatusHistories Guid Id Track order status changes OrderId, ToStatus, ChangedAt, ChangedByUserId
Discounts Guid Id Discount codes and promotions Code (unique), IsActive, StartDate, EndDate, (IsActive + StartDate + EndDate)
DiscountProducts DiscountId, ProductId Many-to-many: Discounts to Products DiscountId, ProductId
DiscountCategories DiscountId, CategoryId Many-to-many: Discounts to Categories DiscountId, CategoryId
PaymentMethods Guid Id Available payment methods Code (unique), IsActive, DisplayOrder
Payments Guid Id Payment transactions OrderId, PaymentMethodId, Status, TransactionId, ReferenceNumber, CreationTime, PaidAt
ShippingMethods Guid Id Available shipping methods Code (unique), IsActive, DisplayOrder
Shipments Guid Id Order shipments OrderId, ShippingMethodId, Status, TrackingNumber, ShippedDate, DeliveredDate
ShipmentItems Guid Id Items in shipments ShipmentId, OrderItemId

Automotive Module (9 Tables)

Vehicle management, parts catalog, compatibility, and services.

Table Name Primary Key Description Key Indexes
VehicleMakes Guid Id Car manufacturers (Toyota, Honda, etc.) Slug (unique), IsActive, DisplayOrder, Name
VehicleModels Guid Id Car models under each make Slug (unique), MakeId, IsActive, DisplayOrder, (MakeId + Name)
Vehicles Guid Id Specific vehicles for sale Slug (unique), ModelId, Year, IsAvailable, IsFeatured, Price, Condition, Vin, CreationTime
PartCategories Guid Id Hierarchical part categories Slug (unique), ParentId, IsActive, DisplayOrder
VehicleParts Guid Id Auto parts catalog Slug (unique), CategoryId, PartNumber, IsActive, IsFeatured, Brand, Price, CreationTime
VehiclePartCompatibilities PartId, ModelId Part compatibility with vehicle models PartId, ModelId, (ModelId + StartYear + EndYear)
ServiceCategories Guid Id Categories for automotive services Slug (unique), IsActive, DisplayOrder
Services Guid Id Automotive services offered Slug (unique), CategoryId, IsActive, IsFeatured, DisplayOrder, CreationTime
VehicleServices VehicleId, ServiceId Many-to-many: Vehicles to Services VehicleId, ServiceId, IsRecommended

Blog Module (4 Tables)

Blog posts, categories, comments, and tagging.

Table Name Primary Key Description Key Indexes
BlogPosts Guid Id Blog articles Slug (unique), IsPublished, IsFeatured, PublishedDate, CategoryId, AuthorId, CreationTime
BlogCategories Guid Id Blog post categories Slug (unique), IsActive, DisplayOrder
BlogComments Guid Id Comments on blog posts (threaded) BlogPostId, UserId, ParentId, IsApproved, CreationTime
BlogPostTags BlogPostId, TagId Many-to-many: Blog posts to Tags BlogPostId, TagId

CMS Module (6 Tables)

Content pages, menus, sliders, FAQs, and videos.

Table Name Primary Key Description Key Indexes
Pages Guid Id Static content pages Slug (unique), IsPublished, DisplayOrder, Template
Menus Guid Id Navigation menu containers Location, IsActive
MenuItems Guid Id Items in menus (hierarchical) MenuId, ParentId, IsActive, DisplayOrder
Sliders Guid Id Homepage/section sliders Location, IsActive, DisplayOrder, (StartDate + EndDate)
FAQs Guid Id Frequently asked questions Category, IsActive, DisplayOrder
Videos Guid Id Video content (YouTube, Vimeo, etc.) Category, Source, IsActive, IsFeatured, DisplayOrder

Notifications Module (3 Tables)

User notifications, templates, and settings.

Table Name Primary Key Description Key Indexes
Notifications Guid Id User notifications (in-app, email, SMS) UserId, Type, IsRead, IsSent, (UserId + IsRead), CreationTime, (RelatedEntityType + RelatedEntityId)
NotificationTemplates Guid Id Templates for different notification types Type (unique), IsActive
UserNotificationSettings Guid Id User notification preferences UserId, (UserId + NotificationType) unique

Identity & User Module (3 Tables)

User profiles, addresses, and authentication tracking.

Table Name Primary Key Description Key Indexes
UserProfiles Guid Id Extended user profile information UserId (unique), NationalCode
UserAddresses Guid Id Saved user addresses UserId, (UserId + IsDefault)
LoginAttempts Guid Id Track login attempts for security UserId, IpAddress, IsSuccessful, CreationTime

System Module (2 Tables)

Configuration, file storage, and audit logging.

Table Name Primary Key Description Key Indexes
ShirinzadConfigs Guid Id Site-wide configuration settings N/A (single row)
FileUploads Guid Id Uploaded files metadata StoredFileName (unique), Category, UploadedByUserId, MimeType, IsPublic, (RelatedEntityType + RelatedEntityId), CreationTime
AuditLogs Guid Id Comprehensive audit trail UserId, ActionType, EntityType, CreationTime, IsSuccessful, (EntityType + EntityId)

Database Indexes & Performance

Strategic Indexing Strategy

The database includes 46+ carefully placed indexes to optimize query performance. Here are the key indexing patterns:

Index Type Count Purpose Examples
Unique Indexes 15+ Enforce uniqueness, prevent duplicates Product.Slug, Order.OrderNumber, Discount.Code
Foreign Key Indexes 25+ Optimize JOIN operations Product.BrandId, Order.UserId, CartItem.ProductId
Status/Flag Indexes 20+ Filter by boolean flags efficiently Product.IsActive, Order.Status, Review.IsApproved
Composite Indexes 15+ Multi-column queries (UserId + IsRead), (ProductId + Group), (MakeId + Name)
DateTime Indexes 10+ Time-based queries and sorting CreationTime, PublishedDate, PaidAt
Search Indexes 5+ Text search and lookup Tag.Name, Category.Name, Product.Code

Performance Impact

Query Speed Improvement

  • Product listing: 50-70% faster
  • Order lookup: 60-80% faster
  • Search queries: 70-90% faster
  • Foreign key JOINs: 40-60% faster

Most Critical Indexes

  • Product.Slug (unique)
  • Product.IsActive
  • Order.OrderNumber (unique)
  • Order.UserId
  • Notification.UserId + IsRead
  • Payment.TransactionId

Index Maintenance

  • Automatically rebuilt during migrations
  • Monitored via performance metrics
  • Optimized for read-heavy workloads
  • Minimal write performance impact

Common Database Queries

Product Queries

Get Active Products with Brand and Category

// EF Core LINQ Query
var products = await _context.Products
    .Include(p => p.Brand)
    .Include(p => p.ProductCategories)
        .ThenInclude(pc => pc.Category)
    .Where(p => p.IsActive)
    .OrderByDescending(p => p.CreationTime)
    .Take(20)
    .AsNoTracking()
    .ToListAsync();

// Uses indexes: Product.IsActive, Product.CreationTime

Search Products by Name or Code

// Search query with multiple filters
var results = await _context.Products
    .Where(p => p.IsActive &&
           (p.Name.Contains(searchTerm) ||
            p.Code.Contains(searchTerm)))
    .OrderBy(p => p.Name)
    .Select(p => new ProductDto
    {
        Id = p.Id,
        Name = p.Name,
        Code = p.Code,
        Price = p.Price,
        BrandName = p.Brand.Name
    })
    .ToListAsync();

// Uses indexes: Product.IsActive, Product.Code

Order Queries

Get User Orders with Items

// Get complete order with items
var order = await _context.Orders
    .Include(o => o.Items)
    .Include(o => o.StatusHistory)
        .OrderByDescending(h => h.ChangedAt)
    .FirstOrDefaultAsync(o => o.OrderNumber == orderNumber);

// Uses indexes: Order.OrderNumber (unique)

Get Orders by Status and Date Range

// Filter orders by status and date
var orders = await _context.Orders
    .Where(o => o.Status == OrderStatus.Processing &&
                o.CreationTime >= startDate &&
                o.CreationTime <= endDate)
    .OrderByDescending(o => o.CreationTime)
    .ToListAsync();

// Uses indexes: Order.Status, Order.CreationTime

Review Queries

Get Approved Product Reviews with Replies

// Get reviews with relationships
var reviews = await _context.ProductReviews
    .Include(r => r.Replies)
    .Include(r => r.Images)
    .Include(r => r.Likes)
    .Where(r => r.ProductId == productId && r.IsApproved)
    .OrderByDescending(r => r.CreationTime)
    .ToListAsync();

// Uses indexes: ProductReview.ProductId, ProductReview.IsApproved

Performance Query Tips

  • Always use .AsNoTracking() for read-only queries
  • Use projections (Select) to retrieve only needed columns
  • Leverage indexes by filtering on indexed columns first
  • Use Include strategically to avoid N+1 query problems
  • Apply pagination with Skip/Take for large result sets
  • Use composite indexes for multi-column WHERE clauses
  • Cache frequently accessed data in Redis (2-hour TTL for products)
  • Monitor query performance with SQL Server Profiler

Migration History

Database Migrations (20+ Applied)

The database schema has evolved through 20+ code-first migrations:

Migration Name Description Date
20251002230111_Initial Initial database schema with ABP framework tables 2025-10-02
20251002233151_AddShirinzadConfig Added site configuration table 2025-10-02
20251003000124_AddCatalogEntities Added Product, Category, Brand, Tag tables 2025-10-03
20251003001930_AddProductGalleryVariantsSpecs Added ProductGallery, ProductVariant, ProductSpec 2025-10-03
20251003003001_AddProductEngagement Added ProductQuestion and ProductAnswer tables 2025-10-03
20251003003551_AddBlogModule Added BlogPost, BlogCategory, BlogComment tables 2025-10-03
20251003005622_AddAutomotiveModule Added Vehicle, VehicleMake, VehicleModel, VehiclePart tables 2025-10-03
20251003010445_AddAutomotiveServices Added Service, ServiceCategory, VehicleService tables 2025-10-03
20251003011058_AddCMSModule Added Page, Menu, MenuItem, Slider, FAQ, Video tables 2025-10-03
20251003013237_AddCartModule Added Cart and CartItem tables 2025-10-03
20251003103204_AddOrderModule Added Order, OrderItem, OrderStatusHistory tables 2025-10-03
20251003105358_AddDiscountModule Added Discount, DiscountProduct, DiscountCategory tables 2025-10-03
20251003110245_AddPaymentModule Added Payment and PaymentMethod tables 2025-10-03
20251003110920_AddShipmentModule Added Shipment, ShipmentItem, ShippingMethod tables 2025-10-03
20251003111912_AddReviewsModule Added ProductReview, ReviewReply, ReviewLike, ReviewImage 2025-10-03
20251003112750_AddWishlistComparisonModule Added Wishlist, WishlistItem, ComparisonList, ComparisonItem 2025-10-03
20251003115128_AddNotificationsModule Added Notification, NotificationTemplate, UserNotificationSettings 2025-10-03
20251003120239_AddFileStorageModule Added FileUpload table for file management 2025-10-03
20251003121237_AddAuthExtensions Added UserProfile and UserAddress tables 2025-10-03
20251003124845_AddBusinessLogicEnhancements Enhanced entities with business logic and validation 2025-10-03
20251003133940_AddAuditLogEntity Added comprehensive audit logging table 2025-10-03
20250104120000_AddLoginAttemptsTable Added LoginAttempt table for security tracking 2025-01-04
Migration Command: dotnet ef migrations add MigrationName --project src/Shirinzad.Shop.EntityFrameworkCore

Related Documentation