Over a million developers have joined DZone.

Short Walks — Data Seeding in Entity Framework Core 2 [Snippet]

DZone's Guide to

Short Walks — Data Seeding in Entity Framework Core 2 [Snippet]

Let's look at how to leverage a helpful feature in Entity Framework Core 2.1 that helps you easily seed data in your database.

· Integration Zone ·
Free Resource

Discover how you can get APIs and microservices to work at true enterprise scale.

Entity Framework Core 2.1 has a nice little feature for seed data. Previously, seeding data quite often involved a series of checks and potential for a script to exist that, if run on the wrong data, would repeatedly re-generate the same seed data.

In 2.1, you can simply override the OnModelCreating function of the data context, like so:

public class ApplicationDbContext : DbContext
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)

    public DbSet<ResourceType> ResourceType { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)

        modelBuilder.Entity<ResourceType>().HasData(new Data.ResourceType()
            Id = 1,
            Name = "Web Site"                

And the framework will calculate whether or not this needs to run to put the data into the state that you've requested.



APIs and microservices are maturing, quickly. Learn what it takes to manage modern APIs and microservices at enterprise scale.

entity framework core ,data ,database ,c# ,.net ,integration ,how-to

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}