Monday, November 23, 2015

Get a list of ApplicationUsers (Users) in MVC 6

If you need a list of all the user in your MVC 6 application.

The following will work from any controller.

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
 var users = Request.GetOwinContext().GetUserManager().Users;

The generated controllers have a line like this:

private ApplicationDbContext db = new ApplicationDbContext();

After the above initialization takes place, you can also get a list of users by simply doing:


Notice, I am NOT using db.ApplicationUsers which you may have been tempted to add to the ApplicationDbContext class using the following:

public DbSet ApplicationUsers { get; set; }

The problem as noted here is that that IdentityDbContext already has the following defined.

public virtual IDbSet Users { get; set; }

So, by adding the ApplicationUsers line above you have added two properties that map to the ApplicationUsers. Here is the error you will get if you have done this:

Multiple object sets per type are not supported. The object sets 'ApplicationUsers' and 'Users' can both contain instances of type 'MyApp.Models.ApplicationUser'.

No comments: