Add data using migration Entity Framework Core without specifying the id

Viewed 14068

I would like to use EF migrations to add some data inside my DB. The fact is that all Id are auto-generated. I found the standard way to achieve it with EF Core, which is the following

modelBuilder.Entity<TypeNote>()
    .HasData(
    new TypeNote { Id = 1, Name = "General" },
    new TypeNote { Id = 2, Name = "E-mail" },
    new TypeNote { Id = 3, Name = "Meeting" },
    new TypeNote { Id = 4, Name = "Reminder" },
    new TypeNote { Id = 5, Name = "Telephone" },
    new TypeNote { Id = 6, Name = "Visit" }
);

My issue here is that I don't want to specify the Id, but it seems that there is no other way using HasData method.

Do you know another way to add data inside DB using migration?

3 Answers

I found a way to do an insert during migration:

        migrationBuilder.InsertData(
            table: "TypeNote",
            columns: new[] { "Name" },
            values: new object[,]
            {
                { "Test" },
                { "Test1" }
        });

The fact is that I wanted to access dbContext inside the migration. Which is impossible because DB is updating.

I think what you are looking for is referred to as "seed data"

Please check out this Microsoft Doc on how to add seed data to your database and let me know whether or not that is what you're looking for.

This is standard for HasData. Auto generated fields are not generated with HasData method.

Please have a look at this EntityFrameworkCore issue.

Related