Tutorials ASP.NET Core Complete Tutorial (ShopNest)

EF Core Code First — Models, Migrations, Database

Learn EF Core Code First — Models, Migrations, Database in our free ASP.NET Core Complete Tutorial (ShopNest) series. Step-by-step explanations, examples, and interview tips on Toolliyo Academy.

On this page
EF Core Code First — Models, Migrations, Database — ShopNest
Article 14 of 75 · Module 2: Entity Framework Core · ShopNest Hospital Management
Target keyword: ef core code first migrations · Read time: ~30 min · .NET: 8 / 9 · Project: ShopNest Hospital Management

Introduction

Code First lets you design Hospital Management entities in C#, then generate and evolve the SQL Server schema with migrations — version control for your database.

After this article you will

  • Create entities with conventions and annotations
  • Run dotnet ef migrations add / database update
  • Understand Up/Down migration methods
  • Seed data with HasData and roll back migrations

Prerequisites

Concept deep-dive

public class Patient
{
    public int Id { get; set; }
    [Required][MaxLength(120)]
    public string FullName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public ICollection<Appointment> Appointments { get; set; }
}

// CLI
dotnet ef migrations add InitialHospitalSchema
dotnet ef database update

Migration Up() creates tables; Down() reverses. Never edit applied migrations in production — add new migration instead.

Hands-on — ShopNest Hospital Management

  1. Entities: Patient, Doctor, Appointment.
  2. Configure relationships in OnModelCreating (preview Fluent API Article 18).
  3. Seed one doctor with HasData.
  4. Inspect generated SQL in Migrations/*.cs.

Common errors & best practices

  • Pending model changes — add new migration.
  • Migration conflict on team — coordinate names; merge carefully.

Interview questions

Q: What does Update-Database do?
A: Applies pending migrations to the database in order.

Summary

  • Migrations version schema changes
  • Code First suits greenfield ShopNest modules
  • HasData seeds reference data

Previous: EF Core Introduction
Next: EF Core CRUD Operations

FAQ

Can I rollback a migration?

dotnet ef database update PreviousMigrationName or remove last migration if not applied to prod.

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

ASP.NET Core Complete Tutorial (ShopNest)
Course syllabus
Module 1: Foundations
Module 2: Entity Framework Core
Module 3: Dependency Injection & Middleware
Module 4: Authentication & Security
Module 5: Web API
Module 6: Advanced Architecture
Module 7: Testing
Module 8: Deployment & DevOps
Module 9: Real-World Projects
Module 10: Advanced Topics
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details