❔ Transform ASP.NET Core IdentityUser into a two-keys table

I need to modify the IdentityUser class so that it has two keys, id and companyId. I tried to extend the IdentityUser class like this
[PrimaryKey(nameof(Id), nameof(CompanyId))]
public class User : IdentityUser
{
public int CompanyId { get; set; }

[ForeignKey(nameof(CompanyId))]
public Company Company { get; set; }

public User() : base() {
}
}
[PrimaryKey(nameof(Id), nameof(CompanyId))]
public class User : IdentityUser
{
public int CompanyId { get; set; }

[ForeignKey(nameof(CompanyId))]
public Company Company { get; set; }

public User() : base() {
}
}
but, when I try to generate the migration data, I have the following error
The derived type 'User' cannot have the [Key] attribute on property 'CompanyId' since primary keys may only be declared on the root type. Move the property 'CompanyId' to 'IdentityUser' or remove 'IdentityUser' from the model by using [NotMapped] attribute or calling 'EntityTypeBuilder.Ignore' on the base type in 'OnModelCreating'.
The derived type 'User' cannot have the [Key] attribute on property 'CompanyId' since primary keys may only be declared on the root type. Move the property 'CompanyId' to 'IdentityUser' or remove 'IdentityUser' from the model by using [NotMapped] attribute or calling 'EntityTypeBuilder.Ignore' on the base type in 'OnModelCreating'.
Of course, since IdentityUser is a type from Microsoft, I don't think it's a good idea to change it. How should I do? Thanks
IdentityUser Class (Microsoft.AspNetCore.Identity.EntityFrameworkCore)
The default implementation of IdentityUser which uses a string as a primary key.
4 Replies
Angius
Angius2y ago
Try the fluent config?
alkasel#159
alkasel#1592y ago
first time I heard of it, I'll take a look, thanks!
Angius
Angius2y ago
In general, prefer fluent config over attributes And prefer convention over fluent config
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.