How to seed in Entity Framework Core 2?

zshanabek picture zshanabek · Jul 17, 2017 · Viewed 46.8k times · Source

I have two tables and I want to fill it using seeds.

I use ASP.NET Core 2 in Ubuntu.

How to populate the data for the two tables where one is connected to the other via foreign key?

The Flowmeter has many notes and note belongs to Flowmeter.

I want to do something like this, but it should be stored in the database:

new Flowmeter 
{
    Make = "Simple model name",
    SerialNum = 45, 
    Model = "Lor Avon", 
    Notes = new List<Note>()
    {
        new Note() { Value = 45, CheckedAt = System.DateTime.Now },
        new Note() { Value = 98, CheckedAt = System.DateTime.Now }
    }
}

Answer

Blake Mumford picture Blake Mumford · May 24, 2018

As of Entity Framework Core 2.1 there is now a new method of seeding data. In your DbContext class override OnModelCreating:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Blog>().HasData(new Blog { BlogId = 1, Url = "http://sample.com" });
}

And for related entities, use anonymous classes and specify the foreign key of the related entity:

modelBuilder.Entity<Post>().HasData(
    new {BlogId = 1, PostId = 1, Title = "First post", Content = "Test 1"},
    new {BlogId = 1, PostId = 2, Title = "Second post", Content = "Test 2"});

Important: Please note you will need to run an add-migration after you enter this data in your OnModelCreating method and Update-Database to update your data.

The official docs have been updated.