DEV Community

Cover image for How to Seed Data in .NET Core Using Entity Framework
Azizul Arif
Azizul Arif

Posted on

How to Seed Data in .NET Core Using Entity Framework

When building applications with .NET Core, it's often necessary to pre-populate the database with some initial data. This process is known as database seeding. In this article, we'll walk through the steps to seed a database with initial data using Entity Framework Core, using a practical example from a project.

What is Database Seeding?

Database seeding is the process of populating a database with an initial set of data when it is created. This can be particularly useful for testing, as it allows you to have some baseline data available in your development environment.

Setting Up the Model

Let's start with a simple model that represents a Villa. This model is part of our domain and will be used to define the structure of the data we want to seed.

using System;

namespace BulkyWeb.Domain.Entity
{
    public class Villa
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string? Description { get; set; }
        public double Price { get; set; }
        public int Sqft { get; set; }
        public int Occupacy { get; set; }
        public string? ImageUrl { get; set; }
        public DateTime CreatedDate { get; set; }
        public DateTime UpdatedDate { get; set; }
    }
}

Enter fullscreen mode Exit fullscreen mode

In this example, the Villa class has several properties like Id, Name, Description, Price, and more, which define the structure of a villa in our system.

Configuring the DbContext

Next, we'll configure our ApplicationDbContext to include seeding logic. The OnModelCreating method is the place where we can define our seed data.

using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Villa>().HasData(
            new Villa
            {
                Id = 1,
                Name = "Royal Villa",
                Description = "Fusce tincidunt maximus leo, sed scelerisque massa auctor sit amet.",
                ImageUrl = "https://placehold.co/600x400",
                Occupacy = 4,
                Price = 200,
                Sqft = 550,
                CreatedDate = DateTime.Now,
                UpdatedDate = DateTime.Now
            },
            new Villa
            {
                Id = 2,
                Name = "Premium Pool Villa",
                Description = "Donec ex mauris, hendrerit quis nibh ac, efficitur fringilla enim.",
                ImageUrl = "https://placehold.co/600x401",
                Occupacy = 4,
                Price = 300,
                Sqft = 550,
                CreatedDate = DateTime.Now,
                UpdatedDate = DateTime.Now
            },
            new Villa
            {
                Id = 3,
                Name = "Luxury Pool Villa",
                Description = "Auctor sit amet. Fusce tincidunt maximus leo.",
                ImageUrl = "https://placehold.co/600x402",
                Occupacy = 4,
                Price = 400,
                Sqft = 750,
                CreatedDate = DateTime.Now,
                UpdatedDate = DateTime.Now
            }
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

In this code, we use the HasData method to seed three different villas into the database. Each villa is defined with its properties, such as Id, Name, Description, Price, etc. The CreatedDate and UpdatedDate fields are set to the current date and time.

Applying the Migration

After setting up the seed data, the next step is to create a migration and apply it to the database.

Step 1: Create the Migration
Run the following command in the Package Manager Console (PMC) or Terminal to create a migration:

add-Migration SeedVillaTable
Enter fullscreen mode Exit fullscreen mode

Step 2: Update the Database

update-Database
Enter fullscreen mode Exit fullscreen mode

This command applies all pending migrations, including the one we just created, to the database. It will also execute the seed data we defined, populating the Villa table with the initial data.

Verifying the Seed Data

After running the migration and updating the database, you can verify that the seed data was successfully added by querying the Villa table in your database. You should see the three villas we defined in the seed data.

Top comments (0)