Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't update the database using Entity Framework Core

I have an ASP.NET Core application that use SQL Server and EF Core. It contains two tables. I successfully created an Entity Framework Core migration and updated the database with it for the first table called Pies.

Then after I added another table called Feedbacks, I created a second migration.

However, when I attempt to update the database, it fails and I get this error:

Error Number:2714,State:6,Class:16
There is already an object named 'Pies' in the database.

Here is the DbContext class:

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }

    public DbSet<Pie> Pies { get; set; }
    public DbSet<Feedback> Feedbacks { get; set; }
}
like image 869
SaTech Avatar asked Oct 16 '19 12:10

SaTech


Video Answer


2 Answers

Since you have messed up the record history of EF Core migrations by deleting a migration file and your snapshot is tainted as well because you re-ran the migrations after deleting one.

Here are the steps you should take:

  1. Delete all remaining migrations
  2. Delete the database
  3. Create a new initial migration
  4. Create a new database.

In the future to avoid these error's use a version control system like git. And before creating any migrations commit. Note you will need to remove the incorrectly applied migration to your database from the _EfMigrations table in your database, since git doesn't version control your database.

like image 154
Anton Toshik Avatar answered Nov 15 '22 07:11

Anton Toshik


This error occurs when there is a difference between the data in the database table and the files in the database.

You most likely created the database once and then deleted the migraine folder

like image 27
Reza Yousefi Avatar answered Nov 15 '22 08:11

Reza Yousefi