Seed Data in Entity Framework Code-First

How to Seed Data into Database using Entity Framework Code-First

In this article, I am going to discuss How to Seed Data into Database Tables in Entity Framework Code-First Approach with Examples. Please read our previous article where we discussed Cascade Delete in Entity Framework Code First Approach.

Seed Data in Entity Framework Code-First Approach

We can insert data into our database tables during the database initialization process. And this is important, if we want to provide some dummy data for our application or if we want to provide some master data for your application such as Country, City, State, Standards, Genders, etc.

To insert data into our database tables during the database initialization process, we have to create a custom Database initializer. In our Database Initialization Strategies in Entity Framework Code-First Approach article we have discussed how to create a custom Database initializer. Once we create the custom Database initializer, we need to override the Seed method and as part of the Seed method we need to write the logic which should enter the data into the database tables.

Example to Understand How to Seed Data in Entity Framework Code-First Approach:

Let us understand how to seed data into database tables using Entity Framework Code-First Approach with an example. Let us first create the following Country, City, and State entities that are going to hold the country, state, and city master data.

using System.ComponentModel.DataAnnotations.Schema;
namespace EFCodeFirstDemo
{
    [Table("CountryMaster")]
    public class Country
    {
        public int CountryId { get; set; }
        public string CountryName { get; set; }
        public string CountryCode { get; set; }
    }

    [Table("StateMaster")]
    public class State
    {
        public int StateId { get; set; }
        public string StateName { get; set; }
        public int CountryId { get; set; }
    }

    [Table("CityMaster")]
    public class City
    {
        public int CityId { get; set; }
        public string CityName { get; set; }
        public int StateId { get; set; }
    }
}
Creating Custom Database Initializer:

To create a custom Database Initializer, we need to create a class by inheriting from any one database Initializer class and we need to override the Seed method. Let us create a class file with the name MyCustomDBInitializer and then copy and paste the following code into it. Here, you can see, we have overridden the Seed method and we have written the code to insert the master data into the database tables.

using System.Collections.Generic;
using System.Data.Entity;
namespace EFCodeFirstDemo
{
    public class MyCustomDBInitializer : DropCreateDatabaseIfModelChanges<EFCodeFirstContext>
    {
        protected override void Seed(EFCodeFirstContext context)
        {
            IList<Country> countries = new List<Country>();
            Country IND = new Country() { CountryName = "INDIA", CountryCode = "IND" };
            Country AUS = new Country() { CountryName = "Austrailla", CountryCode = "AUS" };
            countries.Add(IND);
            countries.Add(AUS);
            context.CountryMaster.AddRange(countries);

            IList<State> states = new List<State>();
            State Odisha = new State() { StateName = "ODISHA", CountryId = IND.CountryId };
            State Delhi = new State() { StateName = "DELHI", CountryId = IND.CountryId };
            states.Add(Odisha);
            states.Add(Delhi);
            context.StateMaster.AddRange(states);

            IList<City> cities = new List<City>();
            City BBSR = new City() { CityName = "Bhubaneswar", StateId = Odisha.StateId };
            City CTC = new City() { CityName = "Cuttack", StateId = Odisha.StateId };
            cities.Add(BBSR);
            cities.Add(CTC);
            context.CityMaster.AddRange(cities);
            base.Seed(context);
        }
    }
}

Now, let us use the above MyCustomDBInitializer in our context class. So, modify the context class as follows:

using System.Data.Entity;
namespace EFCodeFirstDemo
{
    public class EFCodeFirstContext : DbContext
    {
        public EFCodeFirstContext() : base("name=MyConnectionString")
        {
            //Setting the Database Initializer as MyCustomDBInitializer
            Database.SetInitializer(new MyCustomDBInitializer());
        }
        
        public DbSet<Country> CountryMaster { get; set; }
        public DbSet<State> StateMaster { get; set; }
        public DbSet<City> CityMaster { get; set; }
    }
}

Please make sure to have the connection string with the name MyConnectionString within the app.config file or web.config file as shown in the below image.

How to Seed Data into Database Tables in Entity Framework Code-First Approach with Examples

Next, modify the context class as follows.

using System;
using System.Linq;
namespace EFCodeFirstDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (EFCodeFirstContext context = new EFCodeFirstContext())
            {
                Console.WriteLine("Country Master:");
                var Countries = context.CountryMaster.ToList();
                foreach (var country in Countries)
                {
                    Console.WriteLine($"\tCountry ID: {country.CountryId}, Name: {country.CountryName}, Code: {country.CountryCode}");
                }

                Console.WriteLine("State Master:");
                var States = context.StateMaster.ToList();
                foreach (var state in States)
                {
                    Console.WriteLine($"\tState ID: {state.StateId}, Name: {state.StateName}");
                }

                Console.WriteLine("City Master:");
                var Cities = context.CityMaster.ToList();
                foreach (var city in Cities)
                {
                    Console.WriteLine($"\tCity ID: {city.CityId}, Name: {city.CityName}");
                }
                
                Console.WriteLine("Completed");
            }
            Console.ReadKey();
        }
    }
}

With the above changes in place, run the application and verify the database and you should see three database tables are created with the master data as expected in the database. In this case, you will get the following output when you run the above application.

How to Seed Data into Database using Entity Framework Code-First

In the next article, I am going to discuss Database Migration in Entity Framework Code-First Approach with Examples. Here, in this article, I try to explain How to Seed Data into Database Tables in Entity Framework Code-First Approach with Examples. I hope you enjoy this article. Please give your valuable feedback and suggestions about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *