DotNetCore

How to seed your EF Core database




Using Entity Framework Core as an Object Relation Mapper (ORM) for your ASP.net Core Web or API projects, is really easy and you can be up and running with it really quickly.

I have previously discussed how to use EF Core in a seprate class library project and how to configure migrations to enable the update of your database schema.

I generally always follow principles from Code Complete: A Practical Handbook of Software Construction when designing my data tables and schema’s – Chapter 18 is definitely worth a read – the most common mistake I have found when working on legacy applications, is that the developers have often attempted to design their databases for all possible use cases, i.e. Application, Reporting, Data Warehouse, transactional.

This often results in bloated databases and applications which eventually become increasingly difficult to manage, maintain and develop against. This is one of the driving reasons why micro-service architectures have become popular, whereby the application and database are just enough to solve the problem.

You’ll notice that I have tried to keep the database behind this service really small, and only implemented the Minimum Viable Product (MVP) requirements. We only need the ability to Add, Edit and View a list of Web Crawlers and their referer URL’s.

Can’t wait to see it in action ?

Check out the code on GitHub

Code

The Database

The database we are going to seed in this example is a relatively simple database with just enough complexity in it to illustrate how you can cope with most database seeding tasks.

We have 3 tables Threat, ThreatType and Status. Each table has a Primary Key defined and the Threat table has foreign key relationships with both the ThreatType and Status tables.

We are going to seed all 3 of these tables with data, including the relationships.

Context

Although we have created a separate class library project for our EF Core database context class, ApiContext, we are going to develop some extension methods to this class but we are going to add this extension class to our main Api project.

The primary reason being that our Api.Database project is generic mini database project that is going to used for several disconnected micro service applications internally. Each of these micro service applications may have different database seeding requirements and therefore we want to be able to control the seeding on a per project basis.

Add Extension class

Add a new class to the root of the Api project and name it DbContextExtension.cs and add the following code.




We have added a simple boolean method we will call to determine whether all migrations have been applied.

Add Folder for data seeding scripts

Add a folder that will contain your data seeding scripts. This fodler will contain some JSON files which will contain the data required by the applicaiton.

I have just added a folder and called it seed. I have added three JSON files, threats.json , status.json & types.json

Add Seeding Extension Methods

We need to import a few additional namespaces to the DbContextExtension.cs

Add and addtional extension method to the DbContextExtension.csclass, that will be responsible for reading the data from the JSON files and the inserting to the database.

Modify StartUp.cs

We now need to add some code to the StartUp.cs to the Configure method

Summary

The above techniques illustrate how it easy it is to make use of Entity Framework core to create a database and seed it with the default data that it requires.

We used standard JSON data as a source for our data. We also made use of EF Core functions to insert the data.


Gary Woodfine

Freelance Full Stack Developer at threenine.co.uk
Helps businesses by improving their technical proficiencies and eliminating waste from the software development pipelines.

A unique background as business owner, marketing, software development and business development ensures that he can offer the optimum business consultancy services across a wide spectrum of business challenges.
  • Lê Trần Nguyên Lam

    My EnsureSeeded seems never get run. I place breakpoint but it’s skipped…

  • Pingback: Using EF Core in a Separate Class Library project - Gary Woodfine()

  • Nik Godro

    thank you very much!…. There’s so many wrong “solution” out there about seeding in Core 2.0 following this error:
    Unable to create an object of type ‘LibraryContext’. Add an implementation of ‘IDesignTimeDbContextFactory’ to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
    You should add it to your description!
    You’ll be more view-able in search + more click = more view-able + ..= … + ..= …. anyway thanks a lot!

  • Rahul Uttarkar

    Will this work if there are relationships between two tables..? how does this works and objects gets added if dependency exist while picking json objects from files….?

    • Yes, it will work with dependencies. I have defined depedencies in my dataset.

  • Kiran M

    Hi Gary,

    Thanks a ton! Was pondering all over to find an easy way to seed Database with Migrations..

    I had to make some tweaks for EF Core 2.0.. Here is how my DbContextExtensions class looks like –

    public static class DbContextExtensions
    {
    public static bool AllMigrationsApplied(this DbContext context)
    {
    return !context.Database.GetPendingMigrations().Any();
    }
    }

    • Glad it helped. Thanks for the feedback I will take a look at updating it for EF 2.0

π