SQL Server Adding Columns to the Model Table using Entity Framework

wgxvkvu9  于 2023-03-22  发布在  其他
关注(0)|答案(1)|浏览(129)

I created an ASP.NET Core 6 Web API project. After creating the model class, and I did the migrations and all is well. But I deleted the migration file unfortunately.

Now I need to add two new columns the model table, but it show an error while I run the Update-Database command
Error
There is already an object named 'Movies' in the database.

Model class

public class Movie
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int MovieId { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Genre { get; set; }
    public DateTime ReleaseDate { get; set; }
}

I thinks it's trying to create a new table, but I need make changes in the existing table.

Do you have any solution for this situation?

kmbjn2e3

kmbjn2e31#

Since you deleted the initial migration, now when you create a new one, the EF doesn't know that the database model already exists partially, so the new migration tries to create the whole DB model from nothing, insted of building upon the previous migration.

To fix this you can run Update-Database 0 in the Package-Manager console which will reset the database to the empty state.

After that, you apply the new migration with Update-Database

相关问题