Add IdentityUserClaim Navigation to IdentityUser<int>

1

I'm trying to add IdentityUserClaim Navigation to my custom IdentityUser< int >, I tried many ways but it didn't work.

public class AppUser : IdentityUser<int>
{
    [ForeignKey("UserId")]
    public List<AppUserClaim> UserClaims { get; set; }
}

public class AppUserClaim : IdentityUserClaim<int>
{
}

public partial class ApplicationDbContext : IdentityDbContext<AppUser, AppRole, int, AppUserClaim, AppUserRole, AppUserLogin, AppRoleClaim, AppUserToken>
{
    //DBSets
}

If I run the app without migrations (I mean ef migration), then I got the following errors:

Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid column name 'AppUserId'.

SELECT [a].[Id], [a].[AppUserId], [a].[ClaimType], [a].[ClaimValue], [a].[UserId] FROM [AspNetUserClaims] AS [a] WHERE [a].[UserId] = @__user_Id_0

And it's correct, there is no AppUserId column in AspNetUserClaims table.

And when I try to add migrations, then it adds a new column, which I won't it!

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.AddColumn<int>(
        name: "AppUserId",
        table: "AspNetUserClaims",
        type: "int",
        nullable: true);

    migrationBuilder.CreateIndex(
        name: "IX_AspNetUserClaims_AppUserId",
        table: "AspNetUserClaims",
        column: "AppUserId");

    migrationBuilder.AddForeignKey(
        name: "FK_AspNetUserClaims_AspNetUsers_AppUserId",
        table: "AspNetUserClaims",
        column: "AppUserId",
        principalTable: "AspNetUsers",
        principalColumn: "Id",
        onDelete: ReferentialAction.Restrict);
}

How could I say to ef core that I need navigation on existing table relation?

Current DB Schema

c#
entity-framework-core
identity
.net-5
asked on Stack Overflow Apr 24, 2021 by Imran Shamszadeh • edited Apr 24, 2021 by Imran Shamszadeh

1 Answer

1

Ok, you have inherited the correct base IdentityDbContext with the correct generic arguments.

The problem thought is that the base class fluently configures the relationships with no navigation properties. Since the fluent configuration has higher priority than data annotations, the [ForeignKey] attribute is ignored and the navigation property is mapped to a separate relationship with its own FK.

So when you add navigation properties, you need also to override OnModelCreating and reconfigure the relationships after calling the base implementation, e.g.

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    builder.Entity<AppUser>()
        .HasMany(e => e.UserClaims)
        .WithOne()
        .HasForeignKey(e => e.UserId);
}
answered on Stack Overflow Apr 24, 2021 by Ivan Stoev

User contributions licensed under CC BY-SA 3.0