How to Seed Data to Database in EntityFramework

in #utopian-io7 years ago (edited)

What Will I Learn?

Manually writing sql codes to populate your data base can sometimes be a stressful task. It gets worse while working as a team using different databases which implies that every time you pull from your teams git, you will always have to manually write sql codes to fill in the new data your team member has in other to make use of them. Thanks to EntityFramework you no more have to do that and thats exactly what I will be showing you

  • You will learn how to seed data to data base using EntityFramework configurations

Requirements

  • Visual Studio 2013 and above
  • Asp.Net application which uses entityframework code first for creating database
  • EntityFramework nuget package
  • Basic knowledge of asp.net and entityframework

Difficulty

  • Basic

Tutorial Contents

To follow this tutorial, you need an asp.net application that was created using entityframwork code first, but just in case you don't have one, follow my tutorial on Using EntityFramework Code First to Create Database in Asp.net which is in the curriculum to create your application as I will be using this application for the purpose of this tutorial. Please do refer to it.

After creating your Asp.net application as shown in the above tutorial, you should have empty book and bookcategory tables in your sql server database. In your application, open the migration folder and then open the Configuration.cs file as shown below

In the Configuration.cs file, add the following methods to seed data to our different tables.

SeedBookCategory method

private void seedBookCategory(BookShelfContext context)
        {
            context.BookCategory.AddOrUpdate(a => a.CategoryName,
                new BookCategory() { CategoryName = "Poetry" },
                 new BookCategory() { CategoryName = "Novel" },
                  new BookCategory() { CategoryName = "Science" },
                   new BookCategory() { CategoryName = "Fiction" }
            );
        }

SeedBook method

 private void seedBook(BookShelfContext context)
        {
            context.Books.AddOrUpdate(a => a.BookName,
                new Book() { BookName = "Soul of Darkness", Author = "Micheal Stampley", BookCategoryId = 1 },
                 new Book() { BookName = "Utopian Guide", Author = "Micheal Stampley", BookCategoryId = 2 },
                  new Book() { BookName = "Steemit Guide", Author = "Micheal Stampley", BookCategoryId = 3 },
                   new Book() { BookName = "Busy Manual", Author = "Micheal Stampley", BookCategoryId = 4 }
            );
        }

The DbSet.AddOrUpdate() helper extension methods help us add and also edit data we send to our data base, so not only can you add but in the case of any mistake can edit the seed methods and on migration updates will be made to your data base tables.

After Creating your seed methods, you have to initialize them in the automatically generated seed method present in the Configuration.cs file as shown below.

protected override void Seed(BookShelfContext context)
        {
            //  This method will be called after migrating to the latest version.
            seedBookCategory(context);
            seedBook(context);

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data.
        }

N/B To avoid any errors, please ensure that all data entries correspond to the data type you specified in your model class.

After this, launch nuget package manager console and run migrations using the following commands(at this point migration is already enabled).

  • Add-migration Seedmydata

  • Update-database

After this, all your data should be in your database table as shown below. Now whenever you make a pull request, all you have to do is run migration commands and all the data present in your configuration is automatically seed to your database saving you production time and energy.

Curriculum



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @portugalcoin, I just gave you a tip for your hard work on moderation. Upvote this comment to support the utopian moderators and increase your future rewards!

Hey @davidekpin I am @utopian-io. I have just upvoted you!

Achievements

  • Seems like you contribute quite often. AMAZING!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Coin Marketplace

STEEM 0.18
TRX 0.15
JST 0.029
BTC 61952.36
ETH 2417.96
USDT 1.00
SBD 2.64