Add data using migration Entity Framework Core without specifying the id

.net-core c# entity-framework-core

Question

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?

1
1
9/18/2018 11:27:12 AM

Accepted Answer

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.

3
9/19/2018 9:21:02 AM

Popular Answer

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.



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