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

Sean Newcome picture Sean Newcome · Feb 28, 2014 · Viewed 22.6k times · Source

There is a lot of confusion it seems around IdentityDbContext.

If we create two Database Contexts in our application, one for Identity and one for our custom business data, the Identity Database Context inherits from IdentityDbContext while our custom business data inherits from DbContext.

So let's add the following to a controller:

private MyDbContext db = new MyDbContext();
private ApplicationDbContext identityDb = new ApplicationDbContext();

And the following to an Index method in the controller:

var thingsInMyBusinessDb = db.Things.ToList();
var usersInIndentityDb = identityDb.AspNetUsers.ToList(); // THIS WILL HAVE AN ERROR
var roles = identityDb.AspNetRoles.ToList(); // ERROR

You will also notice that the tables in the Indentity Database are not available. Why is this?

Currently as of 2.0.0-beta1 there is a Users and Roles items, but I would have expected the actual tables to be available. And why not? What if I wanted to get to AspNetUserRoles

Sure seems that a lot of confusion and issues with Asp.Net Identity would go away if it were treated like any database context in Entity Framework.

Answer

Anthony Chu picture Anthony Chu · Feb 28, 2014

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.