Hello, people I hope you are having a great day as I am. Today we will continue with the web API series, on my last post we created a pretty basic web API but I intend to continuously make it grow so you can see the process of creating and adding functionality to an actual web API, therefore today we will add seeding functionality with entity framework core.
What is database seeding? 🔎
As the name implies, it is the initial seeding of a database with data. This process often is automated when first executing an application and the data can be dummy data or this can be necessary data such as an initial admin account and password.
Why do I need database seeding ❓
If your application uses authentication and you have administrative accounts you need these accounts to exist before using your application for the first time and that’s when seeding the database comes in handy. Also, a lot of the time when you are developing a new application using a database you realize that you need some actual data to see your application properly working so you proceed to manually insert some dummy data. This can be time-consuming and prone to error tasks, so for the sake of simplicity and to avoid huge mistakes, we use data seeding.
Clone the Github Repo 👨🏾💻
For this example, I will be using the same blog web API that we created and I will just add the corresponding code to integrate the seeding. You can clone the GitHub repo to code along or you can use your own code.
Modify the BlogDbContext class 📖
To apply the seeding we need to override the OnModelCreating method and apply the seeding inside it.
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Post>().HasData(
new Post {Id = 1, Author = "Oscar Montenegro", Title = "My first Post", Body = "Hello world, this is my first post"},
new Post {Id = 2, Author = "Oscar Montenegro", Title = "My second Post", Body = "Hello world, this is my second post"}
);
}
In the code above you can see that we call the ModelBuilder parameter then we call on the Entity which in this case is our blog Post and call on the HasData method to start inserting the records that will work as seeds for our database.
We have to instantiate a new Post object inside the method and fill every one of its properties. You can continue doing this until you have as many records on your database as you desire or need.
And that’s it, as incredible as it sounds that’s all you need to seed your database. If you have more entities you can use the same approach inside the same OnModelCreating method but if you have way more entities and you want to insert several records then the DbContext class can turn huge and unreadable therefore you may find the next approach more useful for your case.
A cleaner & more advanced approach 🤩
For cases where you have more entities and you need to insert several records into your database for your application to properly work and to be able to test it then you should use the model configuration approach as you can see below.
public class PostConfiguration : IEntityTypeConfiguration<Post>
{
public void Configure(EntityTypeBuilder<Post> builder)
{
builder.HasData(
new Post {Id = 1, Author = "Oscar Montenegro", Title = "My first Post", Body = "Hello world, this is my first post"},
new Post {Id = 2, Author = "Oscar Montenegro", Title = "My second Post", Body = "Hello world, this is my second post"}
);
}
}
I created a new directory called config inside my data directory and added this PostConfiguration class that inherits from the IEntityTypeConfiguration interface that provides us with the model configuration functionality. Inside the class, the code is pretty much like the code on the OnModelCreating method except that here we instantly call to the HasData method from the builder parameter.
This way you can extract the database seeding code to a separate model config class for all your entities so your code becomes more readable and clean keeping all the code where it belongs.
Now all you need is to add a new migration using the dotnet cli.
dotnet ef migrations add "Added Data Seeding"
and immediately after this update your database so you can check that you have all your records there.
dotnet ef database update
And there you go, you should now be able to check into your database management system or run the application and see your seeded data. You can check out the code as it ended up being on GitHub.
https://github.com/Osempu/BlogAPI/tree/DataSeeding
Thanks for reading 🌇
That’s it, that’s how easy is to seed your database yet it’s so helpful that can save you a lot of time and help you to avoid errors.
As always thanks for taking the time for reading my post I really enjoy doing this and would love to continue doing it so I would like to ask you for your support not with money or anything like that but with your likes, and comments to improve and also checking my blog where I’m posting all these useful resources. I’,m not sure if you know but a week ago I left my job to dedicate my full time to content creation and some other projects so I would love to count on your support throughout my journey on my personal blog and also on my youtube channel Unit Coding.
Thanks for everything I wish you all the best and I’ll see you in my next post. Goodbye!
Originally published at https://unitcoding.com on March 15, 2023
Top comments (0)