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
- Article 13 — EF Core Introduction
- ShopNest.Web project from prior lessons
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
- Entities: Patient, Doctor, Appointment.
- Configure relationships in OnModelCreating (preview Fluent API Article 18).
- Seed one doctor with HasData.
- 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.