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:
The most important parts:
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.
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).
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.
3. Dependency Injection Services
Again, simple and easy. Adding services to the services collection.
For example, in the web api project. Add the services add in the last picture.
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? 🤔😏😜)