Elegant seeding of data in ASP .NET 6

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 c…


This content originally appeared on DEV Community and was authored by Ssewannonda Keith Edwin

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!


This content originally appeared on DEV Community and was authored by Ssewannonda Keith Edwin


Print Share Comment Cite Upload Translate Updates
APA

Ssewannonda Keith Edwin | Sciencx (2022-05-04T14:48:11+00:00) Elegant seeding of data in ASP .NET 6. Retrieved from https://www.scien.cx/2022/05/04/elegant-seeding-of-data-in-asp-net-6/

MLA
" » Elegant seeding of data in ASP .NET 6." Ssewannonda Keith Edwin | Sciencx - Wednesday May 4, 2022, https://www.scien.cx/2022/05/04/elegant-seeding-of-data-in-asp-net-6/
HARVARD
Ssewannonda Keith Edwin | Sciencx Wednesday May 4, 2022 » Elegant seeding of data in ASP .NET 6., viewed ,<https://www.scien.cx/2022/05/04/elegant-seeding-of-data-in-asp-net-6/>
VANCOUVER
Ssewannonda Keith Edwin | Sciencx - » Elegant seeding of data in ASP .NET 6. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/05/04/elegant-seeding-of-data-in-asp-net-6/
CHICAGO
" » Elegant seeding of data in ASP .NET 6." Ssewannonda Keith Edwin | Sciencx - Accessed . https://www.scien.cx/2022/05/04/elegant-seeding-of-data-in-asp-net-6/
IEEE
" » Elegant seeding of data in ASP .NET 6." Ssewannonda Keith Edwin | Sciencx [Online]. Available: https://www.scien.cx/2022/05/04/elegant-seeding-of-data-in-asp-net-6/. [Accessed: ]
rf:citation
» Elegant seeding of data in ASP .NET 6 | Ssewannonda Keith Edwin | Sciencx | https://www.scien.cx/2022/05/04/elegant-seeding-of-data-in-asp-net-6/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.