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

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 😏.

jke94 / SolutionRepositoryPattern

Let´s go!

Solution and projects
  1. Data Seeding (Data creation and data injection)
  2. 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.
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.
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? 🤔😏😜)

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)