Seeding data to a database is one of those to-dos a backend developer encounters when they have to initialize an API that they are building while in the development phase. This gives the both the backend and front end teams data to work with and to a certain extent the end to end integration required. This eases the work front end teams to integrate with a given API without them referring tom mock ups.
In this quick post, I show you how to seed data to any database in ASP.NET 6 Web API.
Initial Setup
Once you've created your Web API you need to add Entity Framework NuGet packages:
dotnet add package Microsoft.EntityFrameworkCore --version 6.0.3
dotnet add package Microsoft.EntityFrameworkCore.Abstractions --version 6.0.3
dotnet add package Microsoft.EntityFrameworkCore.Analyzers --version 6.0.3
dotnet add package Microsoft.EntityFrameworkCore.Design --version 6.0.3
dotnet add package Microsoft.EntityFrameworkCore.InMemory --version 6.0.3
dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 6.0.3
dotnet add package Microsoft.EntityFrameworkCore.Tools --version 6.0.3
Add Entity
You then create an entity that will be used by the API. Here I used the default WeatherForecast model that comes with the new Web API project from the previous step.
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public string? Summary { get; set; }
}
Add ApplicationDbContext
using Microsoft.EntityFrameworkCore;
namespace SeedWebApplication.Data.Context
{
#nullable disable
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext()
{
}
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<WeatherForecast> WeatherForecasts { get; set; }
}
}
Create a seed class
This is the class that adds a few records to your database.
namespace SeedWebApplication.Data
{
public static class SeedData
{
public static void PopulateDb(IApplicationBuilder app)
{
using var serviceScope = app.ApplicationServices.CreateScope();
AddInitialData(serviceScope.ServiceProvider.GetService<ApplicationDbContext>()!);
}
private static void AddInitialData(ApplicationDbContext context)
{
if (!context.WeatherForecasts.Any())
{
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
var seedForecasts = Enumerable.Range(1, 20).Select(index =>
new WeatherForecast
{
Id = Guid.NewGuid(),
Date = DateTime.Now.AddDays(index),
Created = DateTime.Now.AddDays(-7),
Updated = DateTime.Now.AddDays(-5),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = summaries[Random.Shared.Next(summaries.Length)]
})
.ToList();
context.WeatherForecasts.AddRange(seedForecasts);
context.SaveChanges();
Console.WriteLine("Seeded data to the Database");
}
}
}
}
Modify program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseInMemoryDatabase("inmemo"));
var app = builder.Build();
SeedData.PopulateDb(app);
app.Run();
And yes you have successfully seeded data to your database!
Source code for complete solution can be found on my Github
Until next time, love your neighbor, love yourself!
Top comments (0)