I am using Identity
in my ASP.NET Core MVC project. Except that, I have 2 more models, that I need to join with Id
in AspNetUsers
table. So, I used 3 migrations, 1 is Add-Migration AddAuthentication
and 2 more for models. Then, by using Scaffold-DbContext
I made models from database. And here is the problem, after that, I am getting this error:
The entity type 'AspNetUserLogin' requires a primary key to be defined.
I used to get that error in my project after login, but then, as it says here I just removed those getters and setters. Didn’t work. And here is my last try, I tried to create that column manually, but now, I am getting this error while Update-Database
.
Here is changed part of automatic created migration – there was no Id
column:
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
Id = table.Column<string>(type: "nvarchar(450)", nullable: false),
LoginProvider = table.Column<string>(type: "nvarchar(450)", nullable: false),
ProviderKey = table.Column<string>(type: "nvarchar(450)", nullable: false),
ProviderDisplayName = table.Column<string>(type: "nvarchar(max)", nullable: true),
UserId = table.Column<string>(type: "nvarchar(450)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
I absolutely have no idea what’s wrong. Thanks for help in advance!
2
Answers
Actually, the answer here was quite right. After migrations and creating tables, I have done
Scaffold-DbContext
and got models in other, temporary folder. Then, I just copied it inModels
folder, but, I have changed context a little bit. I removed all ASP staff and kept only my tables. So now, it looks like this:IMPORTANT In automatic created authentication migrations I had to add id's for a couple of tables, to avoid that
the entity type 'AspNetUserLogin' requires a primary key to be defined
error.For creating a relation and adding new columns to AspNetUsers entity you have to define and extra class which must be inherited from IdentityUser. Here is the example
On the context class you must set like this.
This is I think good approach to modify Identity table.