2

I am trying to migrate the changes in models using following code

Add-Migration "InitialCreate"

Migration files are created after executing this command.

enter image description here

I tried to execute following command.

Update-Database

But, I am getting this error:

PM> Update-Database
Build started...
Build succeeded.
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
      Failed executing DbCommand (24ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE [Account] (
          [id] int NOT NULL IDENTITY,
          [payable_amount] varchar(15) NULL,
          [balance_amount] varchar(15) NULL,
          [created_at] datetime NOT NULL,
          [updated_at] datetime NOT NULL,
          [deleted_at] datetime NULL,
          CONSTRAINT [PK_Account] PRIMARY KEY ([id])
      );
Failed executing DbCommand (24ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [Account] (
    [id] int NOT NULL IDENTITY,
    [payable_amount] varchar(15) NULL,
    [balance_amount] varchar(15) NULL,
    [created_at] datetime NOT NULL,
    [updated_at] datetime NOT NULL,
    [deleted_at] datetime NULL,
    CONSTRAINT [PK_Account] PRIMARY KEY ([id])
);
Microsoft.Data.SqlClient.SqlException (0x80131904): There is already an object named 'Account' 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, Action`1 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)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean isAsync, Int32 timeout, Boolean asyncWrite)
   at Microsoft.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String methodName)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String connectionString, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String connectionString, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:1807d8da-31e6-4318-889f-77fff0e3ac25
Error Number:2714,State:6,Class:16
There is already an object named 'Account' in the database.

I have followed given link but it is not helpful.

Link: Update-Database command is not working in ASP.Net Core / Entity Framework Core because object in database already exists

There is already an object named in the database

FYI: I have undo all changes in data model and tried above process but still same error is occurring.

jarlh
  • 42,561
  • 8
  • 45
  • 63
Abhi Singh
  • 321
  • 3
  • 14
  • The Message is clear. There are already objects in your database. If it is an initial script, the database should be empty. The Update-Database command will create all tables in your model. But if there already tables in the database with the same name the command wants to create, the statement will fail. Please remove objects from DB or create a new DB or delete the old DB. – Sebastian Siemens Jan 31 '22 at 07:42
  • Or, if the database contains an __EFMigrations table you make EF think the migration has been run by writing a record into it with the migration name(I don't recommend it). Tell us more about the steps you took to get here; did you create tables in the DB as well as add entities to the context and then add a migration? – Caius Jard Jan 31 '22 at 07:45
  • @CaiusJard I have first created database and then used scaffold commend to import all the tables in Asp.net core project. – Abhi Singh Jan 31 '22 at 07:57
  • I have forgot to make one column nullable of table in DB, So, I decided to achieve it with migration – Abhi Singh Jan 31 '22 at 07:58
  • If you're at very early stages/no data in the db I think I'd empty the db out (or delete it if you have an EnsureCreated call somewhere). – Caius Jard Jan 31 '22 at 08:06
  • 1
    @CaiusJard I just want to update the property of existing column to nullable. For that, do I need to delete whole DB? isn't there any other way? – Abhi Singh Jan 31 '22 at 08:08
  • 1
    There is, but you've kinda painted yourself into a corner: you created a DB, scaffed it, then found a change needed, made the change, added a migration and the migration thinks you've gone from zero to full db, so it's put all the code to make all the tables too. To make the world consistent with where the migration thinks it is you either delete the db and let the migration recreate it or you lie to EF and say the migration has been run. It won't happen next time you migrate; migrations don't look at the db, they look at the diff between the context last time (nothing) and currently(scaff'd) – Caius Jard Jan 31 '22 at 08:11
  • 2
    As such, when developing a db you either modify the db all the time and rescaff it every time, or you modify the context code and use migrations to cause changes in the db. You've effectively started with db first then switched to code first, so you need to get over that initial hill of EF not knowing the DB exists – Caius Jard Jan 31 '22 at 08:14
  • 1
    (If the db is new and nothing in it then it's really trivial to just delete it/rename it and let EF recreate it) – Caius Jard Jan 31 '22 at 08:21
  • 1
    @AbhiSingh This error shows up because you probably have migration that includes table, column same like in one of previous migrations. Check every migration if there is no some duplicates. – Pritom Sarkar Jan 31 '22 at 09:00

1 Answers1

0

(The question is old, but the answer may help others.)

The error is occurring because you have a database and are trying to add a table there that already exists.

Because you are in the early stages of development, the simple solution would be to delete your database and call update-database again to re-scaffold the database using the last migration.

Also, based on what I'm reading in the comments, you may have started with the EF 'database first' approach and then switched to 'code first'. This is not advisable as it leaves EF in a state of confusion. If this is the case, you will need to backtrack, pick one of these two approaches, and stick with it for the lifetime of your model.

Tawab Wakil
  • 1,737
  • 18
  • 33