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

asp.net-authentication asp.net-core entity-framework-core

Question

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

https://docs.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
0
9/14/2017 2:56:49 AM

Popular Answer

Try adding

builder.Entity<IdentityUserRole<int>>().HasKey(p => new { p.UserId, p.RoleId});
0
9/14/2017 3:31:17 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow