Elegant seeding of data in ASP .NET 6
Tags: csharp, dotnet, database
Published: 2022-05-04 14:48:11

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](https://docs.microsoft.com/en-us/aspnet/core/tutorials/min-web-api?view=aspnetcore-6.0&tabs=visual-studio) you need to add Entity Framework NuGet packages:

```ps1
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.
 
```cs
public class WeatherForecast 
{
     public DateTime Date { get; set; }
     public int TemperatureC { get; set; }
     public string? Summary { get; set; }
}
```
#Add ApplicationDbContext

```cs
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.

```csharp
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*

```csharp 
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](https://github.com/edcsu/SeedWebApplication)

Until next time, love your neighbor, love yourself!