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, Action
1 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?
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.
User contributions licensed under CC BY-SA 3.0