5

I have a .NET Core project using EF Core. We already had some tables in the database, so I used EF Core scaffolding command to import all tables into my application.

Everything went fine, I have the models built and I can use those to access database.

Now, I want to change my models just as EF Core Code First approach. I change my model and run a migration.

But my migration fails with this error message:

error CS0102: The type 'mydbContext' already contains a definition for 'Activation'

'Activation' is table in my database. This error is thrown for every table in the database. And I am unable to run the Migration.

My question is, what do I do to run the migration successfully and continue with Code First approach?

I have looked at various places and Microsoft documentation. But none shows how to run migration after a successful scaffolding.

PM> Add-Migration Initial -Context MyApp.Models.mydbContext

error CS0102: The type 'mydbContext' already contains a definition for 
'Activation'

error CS0102: The type 'mydbContext' already contains a definition for 
'Session'

....

I expect to run the migration successfully and be able to update database tables from code.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Afras Company
  • 131
  • 1
  • 4

2 Answers2

8

The simple solution to this issue is to delete all functions in the Up() method (Migrations/initial folder) of the Migration.

You should also delete all the references to existing tables in the Down() method. Otherwise, when you rollback with Remove-Migration you'll end up dropping all the existing tables you started with.

Now run the Update-Database command. This will synchronize the database state between the db and the models.

Now change your models as you wish, add a new migration and then run the Update-Database command.

Hope this helps others!

TidyDev
  • 3,470
  • 9
  • 29
  • 51
Afras Company
  • 131
  • 1
  • 4
  • 2
    You should also delete all the references to existing tables in the Down() method. Otherwise, when you rollback with Remove-Migration you'll end up dropping all the existing tables you started with. – Steve Silberberg May 19 '20 at 20:58
0

another thing that has worked for me is to add the first migration you make to the Sql Migrations table. I don't understand why, but when you make the first migration, it's like it doesn't take into account the snapshot it generates at the beginning, so it wants to create the entire database again.

NioDeTark
  • 41
  • 1
  • 7