Tag Archives: modelBuilder.Entity().HasData()

Short Walks – Data Seeding in Entity Framework Core 2

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.