1
votes

I have .NET Core Project with Entity Framework Core. I created a model from an existing database using the following command

Scaffold-DbContext "Server=.\SQLEXPRESS;Database=DBName;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

The Model was generated and I tried to add migration but the migration that is generated is actually trying to create anew the already existing tables in the database. So when I try to run Update-Database I naturally run into the following error

Applying migration '20200912095755_SetMaxLengthToBookTitle'. Failed executing DbCommand (20ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] CREATE TABLE [Authors] ( [Id] int NOT NULL IDENTITY, [Name] nvarchar(max) NULL, CONSTRAINT [PK_Authors] PRIMARY KEY ([Id]) ); Microsoft.Data.SqlClient.SqlException (0x80131904): There is already an object named 'Authors' in the database. at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)

What is the reason for that and what is the correct way to update database after creating the model from an already existing database in EF Core?

1
It's either code first (with migrations) or DB first (with code generated from tables), you have to pick one - Camilo Terevinto
Yes, but with Entity Framework it was possible to do code first with an existing DB. Is this not possible with Entity Framework Core? - slavhadz
Roll-back your model change so it is as originally scaffolded. Delete all of your migrations, then create a fresh initial migration e.g. dotnet ef migrations add InitialCreate. Then make your model change, and create a second migration. Remove the first migration, and see if EF will apply the second migration. May take some experimenting. - Michael

1 Answers

1
votes

Basically the answer that I found for myself is that I have to add an Initial migration and delete everything in it to make an empty migration. From then on I can proceed by using the code first approach as with the option 'Code first from database' that was available in EF 6.