How to add a foreign key for an Identity user in EF Core?

Let's say I have a model Todowith the corresponding table Todo( DbSet<Todo>) in the database created by EF. The table will store a todo object for each row. Each user (in an ASP.NET Core Identity + IdentityServer application) will be associated with several todo items (one-to-many, a user can have multiple todo items).

As I would do, add a foreign key UserIdto the model Todothat represents the user who owns the todo element.

How can I do this using EF Core using ASP.NET Core Identity validated classes? My intuition was to add the following class model Todo:

public string UserId { get; set; }
[ForeignKey("UserId")]
public ApplicationUser User { get; set; }

As a discovery, it is used ApplicationUser(a custom class model based on the ASP.NET Core Identity standard) for filling with a UserIdforeign key.

Here's the problem: when I start Update-Database, I get an error message! He is speaking The entity type 'IdentityUserLogin<string>' requires a primary key to be defined..

Looking through the code for IdentityUserLogin, I see that it has a property UserIdthat should be considered the primary key, right?

In any case, to make sure it is registered as the primary key, I added this code to the method ApplicationUser OnModelCreating: builder.Entity<ApplicationUser>().HasKey(u => u.Id);. I still get the same error! Not sure what I am doing wrong here :(. Edit: Yes, I called the base class so that there is no problem.

. , , todo , , , . .

+4
2

, , OnModelCreating db, base.OnModelCreating(modelBuilder);.

, .

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // Add Identity related model configuration
    base.OnModelCreating(modelBuilder);

    // Your fluent modeling here
}

: , , . TL;DR , . , , , , , - , , , , , .

.net Identity. , , , . .

Todo. , "" "". .

public class Todo
{
    public int Id { get; set; }
    public string UserId { get; set; }
    public ApplicationUser User { get; set; }
}

ApplicationDbContext DbSet. , ToDo DbSet

add-migration todo , todo. , , FK.

public partial class Todo : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "Todos",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                UserId = table.Column<string>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Todos", x => x.Id);
                table.ForeignKey(
                    name: "FK_Todos_AspNetUsers_UserId",
                    column: x => x.UserId,
                    principalTable: "AspNetUsers",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Restrict);
            });

        migrationBuilder.CreateIndex(
            name: "IX_Todos_UserId",
            table: "Todos",
            column: "UserId");
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable(
            name: "Todos");
    }
}

" ", , , FK . .

public async Task<IActionResult> About()
{
    var user = await _userManager.GetUserAsync(HttpContext.User);
    var todo = new Todo
    {
        User = user
    };
    _context.Todos.Add(todo);
    await _context.SaveChangesAsync();

    return View();
}

: enter image description here

, Todo, - , -, ?

+6

, !

, ApplicationDbContext DbSet ApplicationDbContext.cs - :

public DbSet<MyClass> MyClass { get; set; }

( ): PM > Add-Migration MyClass PM >

+3

Source: https://habr.com/ru/post/1664501/


All Articles