Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 7 of 8
Database Seeding & Test Data
Seeding provides initial reference data (categories, permissions, admin user) that every environment needs from day one. EF Core's HasData seeding runs inside migrations - deterministic, version-controlled, and automatically applied.
Reference Data Seeding Strategy
// ━━ HasData seeding in entity configuration ━━
public void Configure(EntityTypeBuilder<Category> builder)
{
// ... other configuration ...
// Seed with fixed GUIDs (stable across environments)
builder.HasData(
new Category { Id = Guid.Parse("11111111-1111-1111-1111-111111111111"), Name = "Electronics", CreatedAt = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc), UpdatedAt = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc) },
new Category { Id = Guid.Parse("22222222-2222-2222-2222-222222222222"), Name = "Books", CreatedAt = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc), UpdatedAt = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc) },
new Category { Id = Guid.Parse("33333333-3333-3333-3333-333333333333"), Name = "Home & Garden", CreatedAt = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc), UpdatedAt = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc) }
);
}
// ━━ Development seeder - large amounts of fake data ━━
// Only run in Development - never seed production with fakes
public class DevelopmentDataSeeder(AppDbContext dbContext)
{
public async Task SeedAsync(CancellationToken ct = default)
{
if (await dbContext.Products.AnyAsync(ct)) return; // idempotent
var categories = await dbContext.Categories.ToListAsync(ct);
var rng = new Random(42); // fixed seed → reproducible data
var products = Enumerable.Range(1, 100).Select(i =>
new Product
{
Id = Guid.NewGuid(),
Name = $"Product {i}",
Price = Math.Round((decimal)(rng.NextDouble() * 999 + 1), 2),
CategoryId = categories[rng.Next(categories.Count)].Id,
StockQuantity = rng.Next(0, 500),
CreatedAt = DateTime.UtcNow.AddDays(-rng.Next(1, 365)),
UpdatedAt = DateTime.UtcNow,
IsDeleted = false
}).ToList();
dbContext.Products.AddRange(products);
await dbContext.SaveChangesAsync(ct);
}
}
// Register and run in Program.cs (Development only):
if (app.Environment.IsDevelopment())
{
using var scope = app.Services.CreateScope();
var seeder = scope.ServiceProvider.GetRequiredService<DevelopmentDataSeeder>();
await seeder.SeedAsync();
}
// Product entity additions to avoid errors
public static class ProductExtensions2
{
public static int StockQuantity(this Product _) => 0;
}Tip
Tip
Practice Database Seeding Test Data in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of Database Seeding Test Data from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Database Seeding Test Data is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?