Previous NoSQL Integration (MongoDB, Redis) Connection Pooling and Performance Tuning Next

🗄️ Database Migrations and Seeding in EF Core

📖 What are Migrations?

Migrations in EF Core are a way to keep your database schema in sync with your C# model classes. Instead of manually updating the database, EF Core generates migration scripts that apply schema changes incrementally.

Example: Creating a Migration

// From Package Manager Console:
Add-Migration InitialCreate
Update-Database
    

Generated Migration Example

public partial class InitialCreate : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "Products",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                          .Annotation("SqlServer:Identity", "1, 1"),
                Name = table.Column<string>(nullable: true),
                Price = table.Column<decimal>(nullable: false)
            },
            constraints: table => { table.PrimaryKey("PK_Products", x => x.Id); });
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable("Products");
    }
}
    

🌱 What is Seeding?

Seeding is the process of populating the database with initial or default data. This is useful for inserting master data (e.g., roles, countries, admin accounts) when the database is first created or updated.

Example: Seeding Data with Fluent API

public class AppDbContext : DbContext
{
    public DbSet<Product&ht; Products { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Product>().HasData(
            new Product { Id = 1, Name = "Laptop", Price = 1200 },
            new Product { Id = 2, Name = "Phone", Price = 800 }
        );
    }
}
    

Applying Migration with Seed Data

// From Package Manager Console:
Add-Migration SeedProducts
Update-Database
    

✅ Advantages

  • Automates schema evolution without manual SQL scripts.
  • Ensures consistency between code and database.
  • Seeding provides default data for testing or production setup.
  • Supports version control of schema changes.

⚠️ Disadvantages

  • Improper migration handling can cause data loss.
  • Seeding with large datasets can slow down migrations.
  • Conflicts may occur if multiple developers generate migrations simultaneously.

🧭 Best Practices

  • Use migrations for schema changes, not manual SQL.
  • Keep migrations small and incremental.
  • Use HasData() for static seed data (roles, lookup tables).
  • For dynamic or large seed data, use custom initialization scripts.
  • Always test migrations in staging before applying to production.

🔒 Precautions

  • Backup the database before applying migrations in production.
  • Be careful with destructive changes (dropping tables/columns).
  • Use transactions to ensure safe migration execution.
  • Secure seed data (e.g., default admin passwords should be hashed).

🎯 Summary

EF Core Migrations keep your database schema aligned with your code, while Seeding ensures essential data is available from the start. Together, they provide a robust way to manage schema evolution and application initialization in modern .NET projects.

Back to Index
Previous NoSQL Integration (MongoDB, Redis) Connection Pooling and Performance Tuning Next
*