2
votes

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.

1

1 Answers

4
votes

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!