EF Core: update database error: relation "Owner" already exists

Viewed 4155

I try to add migration:

dotnet ef migrations add InitialCreate

and then update the database:

dotnet ef database update

But, I get an error:

Build started...
Build succeeded.
[21:59:12 INF] OnConfigure finish
Applying migration '20201029182606_InitialCreate'.

Failed executing DbCommand (7ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE "Owner" (
"Id" integer NOT NULL GENERATED BY DEFAULT AS IDENTITY,
reputation integer NOT NULL, user_id integer NOT NULL,
user_type text NULL,
profile_image text NULL,
display_name text NULL,
link text NULL,
accept_rate integer NULL,
CONSTRAINT "PK_Owner" PRIMARY KEY ("Id")
);

Npgsql.PostgresException (0x80004005): 42P07: relation "Owner" already exists

at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<g__ReadMessageLong|0>d.MoveNext()
--- End of stack trace from previous location ---
at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<g__ReadMessageLong|0>d.MoveNext()
--- End of stack trace from previous location ---
at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming)
at Npgsql.NpgsqlDataReader.NextResult()
at Npgsql.NpgsqlCommand.ExecuteReaderAsync(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteNonQuery(Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteNonQuery()

Exception data:
Severity: ERROR
SqlState: 42P07
MessageText: relation "Owner" already exists
File: heap.c
Line: 1155
Routine: heap_create_with_catalog
42P07: relation "Owner" already exists

Here on my github i store model (and other source code of service). I remove 'EnsureCreate' code from ApplicationContext file.

How to solve this error? Thank you!

P.S. I remove file appsettings.json where store connetion string:

 {
"Logging": {
 "LogLevel": {
   "Default": "Information",
   "Microsoft": "Warning",
   "Microsoft.Hosting.Lifetime": "Information"
 }
},
 "AllowedHosts": "*",
 "ConnectionStrings": {
  "Questions": "Host=localhost;Port=5432;Database=questiondb;Username=postgres;Password=password"
 },
  "Tags": [
   "ef core",
   "c#",
   "asp.net core",
   "asp.net core webapi"
  ]
  }
2 Answers

In your line 38 I see a problem where you use filed but you need to use the property.

public Owner Owner { get; set; }

But you use

public Owner owner { get; set; }

and that's a problem.

Another solution: as I understand to see your problem that owner table relation already exists. So delete unnecessary relation or use Fluent Api.

Delete Owner table using DB Management Studio or command line then run migration again.

Related