Master the core of Entity Framework Core in Part 4 of our Online Food Ordering System series! We are configuring the ApplicationDbContext class to manage our database tables (Users, FoodItems, Orders). Learn how to use Model Seeding to automatically populate your database with initial data like Categories and Admin users. This step-by-step tutorial is essential for anyone building a CRUD application in ASP.NET Core MVC.
Short Explanation of the Code:
DbContextInheritance: This makes the class a gateway to the database.DbSet<Model>: These lines tell Entity Framework to create tables for your Categories, FoodItems, Users, and Orders.OnModelCreating: This is where we "Seed" the database. It ensures that the moment you create your database, you already have "Pizza" and "Burgers" categories and an "Admin" account ready to use.
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Reflection.Emit;
namespace FoodOrderingSystem.Models
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options) { }
public DbSet<FoodItem> FoodItems { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderItem> OrderItems { get; set; }
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Seed initial data
modelBuilder.Entity<Category>().HasData(
new Category { Id = 1, Name = "Pizza", Description = "Delicious pizzas" },
new Category { Id = 2, Name = "Burgers", Description = "Juicy burgers" },
new Category { Id = 3, Name = "Drinks", Description = "Refreshing beverages" }
);
modelBuilder.Entity<FoodItem>().HasData(
new FoodItem { Id = 1, Name = "Margherita Pizza", Description = "Classic tomato and cheese", Price = 12.99m, CategoryId = 1, ImageUrl = "/images/Margheritapizza.jpg" },
new FoodItem { Id = 2, Name = "Pepperoni Pizza", Description = "Spicy pepperoni with cheese", Price = 14.99m, CategoryId = 1, ImageUrl = "/images/Pepperonipizza.jpg" },
new FoodItem { Id = 3, Name = "Cheeseburger", Description = "Beef patty with cheese", Price = 9.99m, CategoryId = 2, ImageUrl = "/images/Cheeseburger.jpg" }
);
modelBuilder.Entity<User>().HasData(
new User
{
Id = 1,
Username = "admin",
Email = "admin@foodorder.com",
Password = "admin123", // In production, use hashed password!
FullName = "Administrator",
Address = "Admin Office",
Phone = "1234567890",
IsAdmin = true
}
);
}
}
}
Gemini said
To complete your Part 4 setup, you need to add the Connection String to your appsettings.json file. This is the piece of configuration that tells your C# code exactly where your SQL Server is located and what the database name should be.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=.\\SQLEXPRESS;Database=FoodOrderingDB;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True;Encrypt=True"
}
}
Database Initialization
Learn how to automatically initialize and seed your database in ASP.NET Core MVC. In this Part 4 wrap-up, we use
IServiceScopeFactoryto run database commands on startup. We'll explore the difference betweenDatabase.Migrate()andDatabase.EnsureCreated()to help you choose the best workflow for your Food Ordering System development.
Short Explanation of the Code:
CreateScope(): Because theApplicationDbContextis a "Scoped" service, we must create a temporary scope to access it while the app is starting up.GetRequiredService: This pulls your database configuration into this temporary scope so we can talk to SQL Server.EnsureCreated(): This is a powerful command for beginners. It checks if the database exists; if not, it creates the entire schema and runs the Seeding data (like your Pizza and Burger categories) immediately.
// Ensure database is created and seeded
using (var scope = app.Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
// Replace this line in Program.cs:
// context.Database.Migrate();
// With this (for development only):
context.Database.EnsureCreated();
}

Comments
Post a Comment