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?
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.