Entity Framework 7 - run seed at the end of the migration

c# entity-framework entity-framework-core

Question

I have a migration class:

public partial class TestMigration : Migration
{
    protected override void Up(MigrationBuilder db)
    {

At the end of the Up method, I would like to add some data (seed). MigrationBuilder exposes some methods, also Sql(), but I would like to use EF.

Can I inject DbContext here and do some stuff?

1
3
5/20/2016 6:49:36 AM

Popular Answer

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.

60
9/2/2019 10:59:41 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow