DEV Community

Cover image for Using Mockaroo and Entity framework to Seed Sample Data for .NET Applications
Olabamiji Oyetubo
Olabamiji Oyetubo

Posted on

Using Mockaroo and Entity framework to Seed Sample Data for .NET Applications

Testing your applications thoroughly requires diverse sample data that's often time-consuming to create manually. Mockaroo simplifies this process by generating realistic test data quickly, and today we'll explore how to use it.

The only thing you’ll need for this tutorial is Visual Studio community edition. You can download it here

Create a Dataset in Mockaroo

Navigate to the Mockaroo Website,
and define the Dataset fields, I have defined mine like so;

Setting up Mockaroo

Since we’re going to seed the data through EF Core, we’ll select the output format as JSON.

Click on GENERATE DATA and the output file should be downloaded.

Create a Web API project

Open up Visual Studio and click Create a new Project
In the Search Template field, search for ASP.NET Core Web API and click on it.

Give your project a name, I have called mine Mockaroo_Test, then Select .NET 10 as the target framework and leave all the other options as the default values then click Create.

Setting up Web API project

Next, we’re going to install the necessary packages into our project, so open up the package manager console and type in the following commands;

Install-Package Microsoft.EntityFrameworkCore
Enter fullscreen mode Exit fullscreen mode
Install-Package Microsoft.EntityFrameworkCore.InMemory
Enter fullscreen mode Exit fullscreen mode
Install-Package Microsoft.EntityFrameworkCore.Design
Enter fullscreen mode Exit fullscreen mode

Next, Create the a class that has the same structure as the Mockaroo DataSet options we defined earlier

    public class Club
    {
        public int Id { get; set; }

        [JsonPropertyName("club_name")]
        public string ClubName { get; set; }

        [JsonPropertyName("country_location")]
        public string CountryLocation { get; set; }

        [JsonPropertyName("stadium_capacity")]
        public int StadiumCapacity { get; set; }

        [JsonPropertyName("manager_name")]
        public string ManagerName { get; set; }

        [JsonPropertyName("founded_year")]
        public int FoundedYear { get; set; }

        [JsonPropertyName("league_affiliation")]
        public string LeagueAffiliation { get; set; }

        [JsonPropertyName("captain_name")]
        public string CaptainName { get; set; }

        [JsonPropertyName("jersey_color")]
        public string JerseyColor { get; set; }

        [JsonPropertyName("average_attendance")]
        public int AverageAttendance { get; set; }

        [JsonPropertyName("major_rival")]
        public string MajorRival { get; set; }
    }
Enter fullscreen mode Exit fullscreen mode

Now, create a new class called AppDbContext and copy this code into it;

   public class AppDbContext : DbContext
   {
       public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
       {
       }
       public DbSet<Club> Clubs { get; set; }
   }
Enter fullscreen mode Exit fullscreen mode

Since we’re using an Inmemory database, we need to wire it up in our application, so navigate to the Program.cs class and add this piece of code;

builder.Services.AddDbContext<Mockaroo_Test.AppDbContext>(options =>
{
    options.UseInMemoryDatabase("MockarooDemoDb");
});
Enter fullscreen mode Exit fullscreen mode

Seeding the Data

The next step is to move the .json file downloaded from Mockaroo into your application folder, like so;

Move Downloaded Mockaroo file to application folder

Let's then create the class the serializes the data. Do that by creating a class called SeedData and adding this code to it;

    public class SeedData
    {
        public static async Task SeedAsync(AppDbContext context)
        {
            if (context.Clubs.Any()) return;

            var json = await File.ReadAllTextAsync("MOCK_DATA.json");
            var clubs = JsonSerializer.Deserialize<List<Club>>(json);

            context.Clubs.AddRange(clubs!);
            await context.SaveChangesAsync();
        }
    }
Enter fullscreen mode Exit fullscreen mode

The SeedAsync method loads starter information about clubs into the system. It first checks if any clubs already exist, and if the system is empty, it reads club details from a file, converts that information into a usable format, and stores it in the database.

Navigate back to Program.cs and add this piece of code to wire everything up;

using (var scope = app.Services.CreateScope())
{
    var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
    await SeedData.SeedAsync(db);
}
Enter fullscreen mode Exit fullscreen mode

NB; This code snippet should come after the declaration of the app variable

var app = builder.Build();
Enter fullscreen mode Exit fullscreen mode

And that’s it, If you run the application the MockarooDemoDb Database gets seeded with data from our MOCK_DATA.json file.

We can go one step further and visualize the data to make sure.

In the Controllers folder, Create a class called ClubController with this piece of code;

[ApiController]
[Route("api/[controller]")]
public class ClubContronller : ControllerBase
{
    private readonly AppDbContext _context;

    public ClubContronller(AppDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public async Task<ActionResult<List<Club>>> Get()
    {
        var clubs = await _context.Clubs.ToListAsync();
        return Ok(clubs);
    }
}

Enter fullscreen mode Exit fullscreen mode

I’ll be using swagger to visualize the data, you can set up swagger for newer .NET projects using this article here

Run the project and navigate to the swagger page.
When you click execute on the GET Endpoint for clubs, we should see the data

Visualizing the seeded data

If you got lost somewhere along the way, the entire project can be found here

Happy Coding!

Top comments (0)