In a previous post, we explored Entity Framework Core (EF Core) performance enhancements. To make that point in that post, we needed a significant data set to make the point. Creating an example project can be tedious, and a distraction from the point we’re trying to make.
In this post, we’ll see how we can seed our database using EF Core’s seed mechanism with a library called Bogus.
What is Bogus
The dictionary defines the word bogus as being a sham or counterfeit. In the case of software development, Bogus is a test data library that gives us the ability to generate relevant data instances for our purposes.
A simple and sane data generator for populating objects that supports different locales. –Bogus
Bogus is the real deal when it comes to generating fake data. To get started, we need to install the Bogus NuGet package.
dotnet add package Bogus
Once installed, we get access to a library of categories that makes generating test data delightful:
- Addresses
- Commerce
- Company
- Databases
- Dates
- And More…
Let’s take a look at how we can hook into EF Core’s seed mechanism to generate some initial system data.
Sample Code
Within an EF Core DataContext
we can ask it to insert data into our database. Data seeding occurs in the OnModelCreating
method. The method is where we need to use Bogus.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var ids = 1;
var stock = new Faker<Item>()
.RuleFor(m => m.Id, f => ids++)
.RuleFor(m => m.Name, f => f.Commerce.ProductName())
.RuleFor(m => m.Category, f => f.Commerce.Categories(1).First())
.RuleFor(m => m.Price, f => f.Commerce.Price(1).First());
// generate 1000 items
modelBuilder
.Entity<Item>()
.HasData(stock.GenerateBetween(1000, 1000));
}
When we query the database, we see it seeded with 1000 items.
One important note when seeding data in EF Core, we need to be mindful of our Id
properties. The seed mechanism expects us to set this property uniquely and will not do it for us.
Conclusion
We saw that combining the seed mechanism of EF Core with Bogus is a boost to creating sample projects and testing harnesses. Bogus gives us control with a library of relevant data with the ability to define custom behavior through a fluent API. Bogus is a fantastic library, if when we’re not using EF Core. Give it a try and leave a comment below on your thoughts.