Hi. I am trying for a couple of days now and just cannot make it work. It seems like pretty obvious task, however.
public class UserRole : IdentityUserRole<string>
{
public virtual User User { get; set; }
public virtual Role Role { get; set; }
}
public class User : IdentityUser
{
public virtual ICollection<UserRole> UserRoles { get; set; }
}
public class Role : IdentityRole
{
public virtual ICollection<UserRole> UserRoles { get; set; }
}
public class IdentityContext : IdentityDbContext<User, Role, string>
{
public IdentityContext(DbContextOptions<IdentityContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>()
.HasMany(e => e.UserRoles)
.WithOne()
.HasForeignKey(e => e.UserId)
.IsRequired()
.OnDelete(DeleteBehavior.NoAction);
}
services
.AddIdentity<User, Role>(options =>
{
options.Password.RequireDigit = false;
options.Password.RequiredLength = 1;
options.Password.RequireUppercase = false;
options.Password.RequiredUniqueChars = 0;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireLowercase = false;
options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<IdentityContext>()
.AddDefaultTokenProviders();
What I have tried:
I just want for a start to get join table joined to a user object, but:
var q = userManager.Users.Include(x => x.UserRoles).ToList();
q.UserRoles count is zero.
I have tried everything what is available on the net, nothing works in my case. UserRoles join table has always zero roles. I have one user and one role, and user is assigned to this role.
Please help
P.S. I can see that
IdentityDbContext
already is doing all required initialisation in its
OnModelCreating
.
If I change:
public sealed class User : IdentityUser
{
public ICollection<IdentityUserRole<string>> UserRoles { get; set; }
}
Then here:
<pre>var q = userManager.Users.Include(x => x.UserRoles).ToList();
I have UserRoles object, which has one item. But I cannot do further includes to get actual Role object.