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

前端 未结 4 423
星月不相逢
星月不相逢 2020-11-30 03:08

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 c

4条回答
  •  感动是毒
    2020-11-30 03:54

    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
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }
    
        public DbSet UserRoles { get; set; }
        public DbSet Claims { get; set; }
        public DbSet 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.

提交回复
热议问题