Seed Database in Entity Framework

In our last tutorial, we looked at how to create custom database initializer in entity framework. One of the main use of creating the custom database Initializer is to seed the database with useful data. In this tutorial let us look at the how to seed database in Entity Framework

Seed Database in Entity Framework

Seeding the database means pre-populating the database with default data. This is useful in scenarios where you want to provide some test data in the development environment. You could use this to set up the application for the first time in a production environment by providing the sample or useful master data.

You need to use the Custom database initializers to use the Seed method.

Using inbuilt Database Initializers

The Entity Framework built in initializers contains the seed method. This method actually does nothing. So you need to override the seed method with your own implementation.

In the above example, our custom database initializer inherits from the built in initializer DropCreateDatabaseAlways. We then added seed method which overrides the base class’s seed method. We then added two users to the user’s collection. Finally, SaveChanges is called to persist the data to the database.

The seed method is called immediately after a new, empty database is created. Seed method is never called for an existing database. That is because the existing database might already have data in it.

Seeding Database using IDatabaseInitializer

The built in initialisers has already implemented the seed method and calls the method when InitializeDatabase is called. In case you want to create the custom initializer using the interface IDatabaseInitializer, then you need to write the seed method and call it.

In the above example, we have created EFInitializer which implements the interface IDatabaseInitializer. The above code deletes and creates the database, which is what DropCreateDatabaseAlways built in initializer does. Seed method is called after the database is created. The method is similar to the previous example.

Seeding Data In Relationships

In Entity Framework, you can define relationships between your models.  You can read about Relationships in Entity Framework. Consider you have model Role model along with user model. The User and Role model has a One to Many Relationship between them.

And our seed method will look like this

Conclusion

In this tutorial, we looked at the database seed method. We saw how to create seed method when using the Built-in Initializer. We also looked at how to create the same, while inheriting from the IDatabaseInitializer.

Source Code

You can download the source code from the GitHub repository

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top