Search code examples
c#asp.net-coreentity-framework-coremariadbpomelo-entityframeworkcore-mysql

Extending UserRole primary key with additional columns ASP.NET Core EF


I have an ASP.Net Core project with Identity models. It uses a 10.4.17-MariaDB database with the Pomelo MySQL provider. The project is already used in production, but I would like to extend the UserRole with new keys in the latest version. I have defined my own UserRole class that extends the IdentityUserRole like this:

public class UserRole : IdentityUserRole<String>
{
    [Key]
    public Guid OrganizationId { get; set; }
    [Key]
    public DateTime Join { get; set; }
    ...
}

So I would like my user to have multiple roles in multiple organizations with multiple 'join' dates. I manually added the HasKey line to the entity in DB context:

modelBuilder.Entity<UserRole>(entity =>
{
    entity.HasKey(m => new { m.UserId, m.RoleId, m.Join, m.OrganizationId });
    entity.Property(m => m.UserId).HasMaxLength(127);
    entity.Property(m => m.RoleId).HasMaxLength(127);
    entity.Property(m => m.OrganizationId).HasMaxLength(127);
    entity.Property(m => m.Join);
    ...
});

When I add a migration with these changes and try to execute it I get the following error:

Failed executing DbCommand (31ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
ALTER TABLE `AspNetUserRoles` ADD CONSTRAINT `FK_AspNetUserRoles_AspNetRoles_RoleId` FOREIGN KEY (`RoleId`) REFERENCES `AspNetRoles` (`RoleId`) ON DELETE CASCADE;

Why is the migration trying to make a reference to RoleId if the primary key of the AspNetRoles table is called Id?

I checked the first migration with the Script-Migration command and the foreign key is correctly referenced to Id during the table creation.


Solution

  • Turns out it was a bug in the alpha version of the Pomelo library that I used. The bug was already fixed in the nightly build by that time. See the issue #1371 on Github.