Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

SnapLogic is the leading self-service enterprise-grade integration platform. Download the 2018 GartnerMagic Quadrant for Enterprise iPaaS or play around on the platform, risk free, for 30 days.

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)
    {
        base.OnModelCreating(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.

References

https://docs.microsoft.com/en-us/ef/core/modeling/data-seeding

With SnapLogic’s integration platform you can save millions of dollars, increase integrator productivity by 5X, and reduce integration time to value by 90%. Sign up for our risk-free 30-day trial!

Topics:
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 }}