Creating the Database: EF Core Migrations & SQL Server Setup | Food Ordering System [Part 5]

 


Stop building static apps and start managing real data! In Part 5 of our Online Food Ordering System series, we dive deep into Entity Framework Core Migrations. Learn exactly how to use the Add-Migration and Update-Database commands in ASP.NET Core MVC to transform your C# Models into a fully functional SQL Server database. Whether you are a student working on a final year project or a developer learning EF Core 2026, this step-by-step guide covers everything from initial migration to verifying your tables in SSMS. Don't let database errors stop your progress—master the data layer today!

Code Explanation

  • using (var scope = app.Services.CreateScope()): In ASP.NET Core, the ApplicationDbContext is a "Scoped" service, meaning it is created and destroyed with each web request. Since the application is just starting up and there is no web request yet, we must manually create a "scope" to access these services.

  • var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();: This line reaches into the service container we just opened and pulls out your ApplicationDbContext. This allows the code to interact with your specific database configuration.

  • context.Database.EnsureCreated();: This is the action command. It checks if the database specified in your connection string exists. If it does not, it creates the database and all the tables defined by your DbSet properties. It also runs the seed data (like your initial Categories and Admin user) that you defined in the OnModelCreating method.

  • Development Note: As your comments suggest, EnsureCreated() is perfect for early development because it is fast and simple. However, it does not support "Migrations." Once you begin changing your data models frequently, you should switch to context.Database.Migrate().

Program.cs - Database Initialization
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();
}
After updating appsettings.json, run:

Code Explanation

  • dotnet ef: This is the command-line interface (CLI) tool for Entity Framework Core.

  • database update: This specific command checks the __EFMigrationsHistory table in your database to see which migrations have already been applied and runs any new ones.

  • The Result: After running this, your tables (Categories, FoodItems, etc.) will be created in SQL Server, and your seed data will be inserted.

Terminal - Package Manager Console
dotnet ef database update dotnet tool install --global dotnet-ef

Run Migrations

Open Package Manager Console (Tools → NuGet Package Manager → Package Manager Console) or use terminal:
Terminal - Package Manager Console
# Create initial migration
dotnet ef migrations add InitialCreate

# Apply to database
dotnet ef database update
If you already have a Migrations folder and get errors, try:
Code Explanation
  • dotnet ef database drop --force: This permanently deletes the existing database from SQL Server. The --force flag ensures the database is dropped even if there are active connections. Warning: This will delete all your stored data.

  • dotnet ef migrations remove: This deletes the last migration files created in your project, allowing you to start your migration history over from scratch.

  • dotnet ef migrations add InitialCreate: This generates a brand-new migration file based on your current ApplicationDbContext and Model classes.

  • dotnet ef database update: This creates the new database in SQL Server and applies your seeding data (Categories, FoodItems, and Admin User).

Terminal - Database Reset
# Reset and recreate (Development only - loses data)
dotnet ef database drop --force
dotnet ef migrations remove
dotnet ef migrations add InitialCreate
dotnet ef database update

Alternative: Auto-Create Tables (Development Quick Start)

If you want tables created automatically on first run (good for testing), update Program.cs:

Code Explanation

  • context.Database.Migrate(): This is the standard way to apply pending migrations to a database. It tracks history and is the "best practice" for production environments.

  • context.Database.EnsureCreated(): This command is a "quick start" tool. It checks if the database exists; if not, it creates the database and all tables based on your current ApplicationDbContext. It also triggers any seed data you have defined, such as your initial categories and admin user.

  • Development Only: You use this during the early stages of your Food Ordering System because it is faster than managing migration files. However, it does not support future schema changes—if you change a model later, you must delete the database and let it recreate it.

Program.cs - Database Logic
// Replace this line in Program.cs:
// context.Database.Migrate();

// With this (for development only):
context.Database.EnsureCreated();

Comments