Mark G
Mark G

Reputation: 3116

Updating Identity in ASP.NET Core 2.0

I'm having an issue trying to replace IdentityUser navigation properties in ASP.NET Core Identity which was a breaking change in 2.0 update.

I looked at Add IdentityUser POCO Navigation Properties, but there was scant explanation on how to actually do this.

In ApplicationUser.cs I added the following:

public virtual ICollection<IdentityUserRole<string>> Roles
    { get; } = List<IdentityUserRole<string>>();

But when I attempted to use that navigation property it used ApplicationUserId instead of UserId.

Any suggestions would be welcome as this isn't intuitive, hopefully the identity team can further elaborate in the documentation.

Upvotes: 3

Views: 1970

Answers (2)

Mark G
Mark G

Reputation: 3116

Adding the following to OnModelCreating in ApplicationDbContext.cs fixed the problem for me which I found from GitHub issue How to include Roles in IdentityUser?

builder.Entity<ApplicationUser>().HasMany(p => p.Roles)
    .WithOne().HasForeignKey(ur => ur.UserId).IsRequired();

Upvotes: 1

amustelier
amustelier

Reputation: 91

In my case I have three derived clases ApplicationUserClaim, ApplicationUserLogin, ApplicationUserRole. I do that because I need to add some custom properties.

Derived classes without added properties should look like this.

public class ApplicationUserLogin : IdentityUserLogin<string>
{
    public virtual ApplicationUser ApplicationUser { get; set; }
}


public class ApplicationUserRole: IdentityUserRole<string>
{
    public virtual ApplicationUser ApplicationUser { get; set; }
}


public class ApplicationUserClaim: IdentityUserClaim<string>
{
     public virtual ApplicationUser ApplicationUser { get; set; }
}

On your ApplicationUser add the following code:

public virtual ICollection<ApplicationUserRole> Roles { get; } = new List<ApplicationUserRole>();

public virtual ICollection<ApplicationUserClaim> Claims { get; } = new List<ApplicationUserClaim>();

public virtual ICollection<ApplicationUserLogin> Logins { get; } = new List<ApplicationUserLogin>();

On your ApplicationDbContext add the following code:

modelBuilder.Entity<ApplicationUserClaim>().HasOne(pt => pt.ApplicationUser).WithMany(t => t.Claims).HasForeignKey(pt => pt.UserId);

modelBuilder.Entity<ApplicationUserRole>().HasOne(pt => pt.ApplicationUser).WithMany(t => t.Roles).HasForeignKey(pt => pt.UserId);

modelBuilder.Entity<ApplicationUserLogin>().HasOne(pt => pt.ApplicationUser).WithMany(t => t.Logins).HasForeignKey(pt => pt.UserId);

Make a Migration and you are done.

Upvotes: 4

Related Questions