4.3: Seeding the Database
The next step is to get the data in our database.
Add Newtonsoft.Json package
By manually adding it to your EFConnect.Data.csproj
file, using the command prompt, or by using the NuGet package manager console, add a reference to Newtonsoft.Json to your .Data project.
Add Seed Class
In your .Data
project, add a new class called Seed.cs
.
We won't be using our Service to add users here - so, we'll also be borrowing the CreatePasswordSalt()
method from our AuthService
.
Register the Seed Class in Our Services
In the Startup.cs
file in your .API
project, register the Seed
class as transient:
Remember what transient was? This will create a new instance of our Seed class only once - in this case when the project starts. This is just to ensure our data stays the same while developing. If we want to get our users back to the original state we can reseed the database - we'll also wipe out test data and go back to the original state.
Add Seeding to the Middleware Pipeline
First, add it as a parameter to the Configure()
method:
Then, call it in the pipeline:
Run the Project and Seed the Data
Now, when we run the application, the our database will be seeded with our data!
Open up your terminal, navigate to the root of the .API project and run it:
Check the Database
Open up SQL Server Management Studio and verify that the data was added.
Looks good! We've got a big list of users to work with now.
You can comment out the seeder.SeedUsers() method in your middleware so it doesn't run every time you start the project up.
Last updated