Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add data using migration Entity Framework Core without specifying the id

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?

like image 239
Frix G Avatar asked Sep 18 '18 08:09

Frix G


People also ask

How do you specify context in add 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.

How do I code my first migration to an existing database?

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.

Can I use ef core without migration?

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.


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

like image 133
Frix G Avatar answered Oct 22 '22 14:10

Frix G