Migrating Auth to Core 2.0: The entity type 'IdentityUserRole<int>' requires a primary key to be defined

884 views Asked by At

I am migrating my app to ASP.Net Core 2.0.

https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x

In the above article, it has the following mapping:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);
    // Customize the ASP.NET Identity model and override the defaults if needed.
    // For example, you can rename the ASP.NET Identity table names and more.
    // Add your customizations after calling base.OnModelCreating(builder);

    builder.Entity<ApplicationUser>()
        .HasMany(e => e.Claims)
        .WithOne()
        .HasForeignKey(e => e.UserId)
        .IsRequired()
        .OnDelete(DeleteBehavior.Cascade);

    builder.Entity<ApplicationUser>()
        .HasMany(e => e.Logins)
        .WithOne()
        .HasForeignKey(e => e.UserId)
        .IsRequired()
        .OnDelete(DeleteBehavior.Cascade);

    builder.Entity<ApplicationUser>()
        .HasMany(e => e.Roles)
        .WithOne()
        .HasForeignKey(e => e.UserId)
        .IsRequired()
        .OnDelete(DeleteBehavior.Cascade);
}

It looks fine to me. However, when I run

dotnet ef migrations add InitialCreate

I get the following error:

The entity type 'IdentityUserRole' requires a primary key to be defined.

ApplicationUser is defined as follows:

public class ApplicationUser : IdentityUser
{
    /// <summary>
    /// Navigation property for the roles this user belongs to.
    /// </summary>
    public virtual ICollection<IdentityUserRole<int>> Roles { get; } = new List<IdentityUserRole<int>>();

    /// <summary>
    /// Navigation property for the claims this user possesses.
    /// </summary>
    public virtual ICollection<IdentityUserClaim<int>> Claims { get; } = new List<IdentityUserClaim<int>>();

    /// <summary>
    /// Navigation property for this users login accounts.
    /// </summary>
    public virtual ICollection<IdentityUserLogin<int>> Logins { get; } = new List<IdentityUserLogin<int>>();

    public string FullName { get; set; }
}

Is there something wrong with the mapping?

1

There are 1 answers

2
Raphael Müllner On

Try adding

builder.Entity<IdentityUserRole<int>>().HasKey(p => new { p.UserId, p.RoleId});