Can't use migrations in EF Core: "42P07: relation "AspNetRoles" already exists"


I have strange issue which I can't find solution for.

The stack is: NET Core 2, EF, PostgreSQL. I use .NET Core Identity with User : IdentityUser to extend base user model with additional fields.

After I create first migration, drop whole database and try to dotnet ef database update I always get an error: 42P07: relation "AspNetRoles" already exists

Even with this error, the database and tables are created but it makes migrations useless as it does not save applied migrations so I can't update DB with following changes...

fail: Microsoft.EntityFrameworkCore.Database.Command[200102] Failed executing DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] CREATE TABLE "AspNetRoles" ( "Id" text NOT NULL, "ConcurrencyStamp" text NULL, "Name" varchar(256) NULL, "NormalizedName" varchar(256) NULL, CONSTRAINT "PK_AspNetRoles" PRIMARY KEY ("Id") ); Npgsql.PostgresException (0x80004005): 42P07: relation "AspNetRoles" already exists at Npgsql.NpgsqlConnector.d__148.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at System.Runtime.CompilerServices.ValueTaskAwaiter1.GetResult()
at Npgsql.NpgsqlConnector.d__147.MoveNext()

asked on Stack Overflow Nov 21, 2017 by M U • edited Nov 21, 2017 by M U

2 Answers


The reason was pretty simple. I was calling EnsureCreated in Startup.cs which was getting conflict with migrations as working different way. Thankfully EF Core owners made it clear for me on GitHub.

So to summarize - if you want to use Migrations, you can't use EnsureCreated.

answered on Stack Overflow Dec 8, 2017 by M U

I was doing something really dumb! I copied the connection string from another micro service and it had the wrong Database in the connection string - that database already had the table that the error was complaining about! Block Copy strikes again!

answered on Stack Overflow Feb 3, 2020 by JD Hicks

User contributions licensed under CC BY-SA 3.0