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?
Using multiple context types One way to create multiple migration sets is to use one DbContext type per provider. Specify the context type when adding new migrations. You don't need to specify the output directory for subsequent migrations since they are created as siblings to the last one.
Run the Add-Migration InitialCreate command in Package Manager Console. This creates a migration to create the existing schema. Comment out all code in the Up method of the newly created migration. This will allow us to 'apply' the migration to the local database without trying to recreate all the tables etc.
If you'd like to access data from an existing database and tables with Entity Framework (EF) Core in your ASP.NET Core Web API project, you can try to use Scaffold-DbContext command or dotnet ef dbcontext scaffold command to generate code for a DbContext and entity types for your database.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With