May be i'm missing something very obvious. But i haven't been able to figure out a way to add a new column to an existing table/model in EF Core.
This is the documentation that I'm following: https://learn.microsoft.com/en-us/ef/core/miscellaneous/cli/powershell
And this is what i have done so far:
So how do i update an already existing table table ? 2 ways i can think of are:
But i feel there should be a better way to do this.
This is how i resolved the issue. Not sure if it is the perfect way.
Key is NOT to delete the initial migration, before you create the new migration.
Adding the steps here:
This is a way which helped me to add a new column to the existed database without losing data:
I've written this command into Package Manager Console to the Project which contains my Model
add-migration MyFirstMigration
The above command created a class with a lot of code:
public partial class MyFirstMigration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
...
// The code is omitted for the brevity
...
}
}
I've deleted all generated code and added the following code snippet into the above method Up(MigrationBuilder migrationBuilder)
:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>("Password", "Users", "varchar(255)",
unicode:false, maxLength: 255, nullable: true);
}
Then it is necessary to write the following command into Package Manager Console to add a column into your database:
Update-Database
I kinda did a mixture of what @Boney and @StepUp suggested and it ran without hitches. Here's what I did. Assume a have a table Period that I decided to add an additional column PeriodTypeId.
Add-Migration -Name OVCDbMigrationsUpdated -Context DbContext
This created a new migration file with name: OVCDbMigrationsUpdated.
Update-Database -verbose -Migration OVCDbMigrationsUpdated -Context DbContext
My DB was updated successfully with the new column.
I was running into a similar issue with EF Core and an existing database with some of the model fleshed out, but I was adding a new model (that already had a table) and was getting the error
There is already an object named 'tableN' in the database.
The way I got this to work on an existing database was:
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