.NET 5 (C#) + EF Core: Data seeding (🍺) when the web application is launched 🔛

Javier Carracedo
3 min readSep 1, 2021

--

A little example of how seed random data in the database when the web application is launched. Using SQL Server as data provider and code first strategy to build the application.

How to seed random data in a database with EF Core when the application is launched?

This could be util to build a little project and get data since a Web API project for example 😏.

For the following example, I’m going to use myself code from this GitHub repositoy:

jke94 / SolutionRepositoryPattern

Let´s go!

Solution and projects

The most important parts:

  1. EF Core Provider
  2. Data Seeding (Data creation and data injection)
  3. Dependency Injection Services

1. EF Core Provider

First, we need the database provider. In this case I have used SQL Server as database, for this reason, I will use the corresponding database provider.

Services extension project to create and organice all services.

Using “Microsoft.EntityFrameworkCore.SqlServer” NuGet Package I have access to the databse adding the context of the database futhermore the connection string (DefaultConnection string is stored in “appsettings.json”).

As resume, I am deleting and I am creating (line 22 and 23) always that the application is launched the database. Applying the last migration of the database.

“RepositoryContext” is the DbContext application (line 12) using SQL Server Database with the connection string “DefaultConnection” (using “appsettings.json” in MyWebAPI Project).

RepositoryContext (Dabase context)

2. DataSeeding (Data creation and data inyection)

Easy. In this pick, I have called to services collection (injection in StartUp.cs class) and creating different data arrays to create data and save in the database.

Get data and inyection data.

3. Dependency Injection Services

Again, simple and easy. Adding services to the services collection.

Adding services.

For example, in the web api project. Add the services add in the last picture.

MyWebAPI Project — Add services.

Conclusions: Why is this util?

  • Uncople services from the Web API project. I 💛 depency injection services.
  • Data seeding for test quickly a simple WEB API Project.
  • It´s scalable. For each, table of the database, build a class for seed the database and call it from the data seeded provider.
  • You can configuring different databases (SQLite, SQL Server, etc). with the providers (next article? 🤔😏😜)

Thanks!

--

--

Javier Carracedo

Hi! SW Engineer from León (Spain) . I ❤ my work, I like improve and to grow my knowledge about different technologies. SW Engineer at HP SCDS - León (Spain)