Why is Asp.Net Identity IdentityDbContext a Black-Box?

The ApplicationDbContext‘s Users and Roles properties are mapped to the AspNetUsers and AspNetRoles tables, and the rest of the entities (Claims, Logins, UserRoles) are mapped automatically via navigation properties. As far as I know, the prefixing of table names with “AspNet” are the only custom mappings in ApplicationDbContext, everything else is just Entity Framework Code First conventions.

If you need direct access to the tables via the ApplicationDbContext, you can do so like this…

using (var context = new ApplicationDbContext())
{
    var users = context.Users.Include(u => u.Claims)
                             .Include(u => u.Logins)
                             .Include(u => u.Roles)
                             .ToList();

    var roles = context.Roles.ToList();
}

You can access a user’s roles, claims, and logins via navigation properties on the IdentityUser entity (from the Users DbSet). If you want to query them directly, add them explicitly as DbSets on the context…

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<IdentityUserRole> UserRoles { get; set; }
    public DbSet<IdentityUserClaim> Claims { get; set; }
    public DbSet<IdentityUserLogin> Logins { get; set; }

}

And query them like this…

var claims = context.Claims.ToList();
var userRoles = context.UserRoles.ToList();
var logins = context.Logins.ToList();

ASP.NET Identity 2.0 exposes Users and Roles IQueryables on the Manager classes for convenience, but it doesn’t provide any added functionality over what was available from the DbContext.

Leave a Comment