2

I have following methods to get the list of roles stored in AspNetRoles

    [AllowAnonymous]
    public async Task<ActionResult> Register()
    {
        //Get the list of Roles
        ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");

        return View();
    }

then I get it in view as follows

    <div class="form-group">
        <label class="col-md-2 control-label">
            Select User Role
        </label>
        <div class="col-md-10">
            @foreach (var item in (SelectList)ViewBag.RoleId)
            {
                <input type="checkbox" name="SelectedRoles" value="@item.Value" class="checkbox-inline" />
                @Html.Label(item.Value, new { @class = "control-label" })
            }
        </div>
    </div>

but once I load the page I'm getting Object reference not set to an instance of an object. error

Line 175: ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");

This is RoleManager Definition

    public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
    }

this is ApplicationRoleManager Model

// Configure the RoleManager used in the application. RoleManager is defined in the ASP.NET Identity core assembly
public class ApplicationRoleManager : RoleManager<ApplicationRole>
{
    public ApplicationRoleManager(IRoleStore<ApplicationRole, string> roleStore)
        : base(roleStore)
    {
    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        return new ApplicationRoleManager(new ApplicationRoleStore(context.Get<ApplicationDbContext>()));
    }
}
kez
  • 2,273
  • 9
  • 64
  • 123
  • Possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Hamid Pourjam Mar 07 '16 at 07:39
  • Possible duplicate http://stackoverflow.com/questions/34975075/asp-mvc-how-get-roles-from-applicationuser/34975588#34975588 – IMujagic Mar 07 '16 at 08:26
  • @IMU actually I want get available roles , not assigned user's role or current users – kez Mar 07 '16 at 08:30
  • @dotctor appreciate your suggestion , but I read that question very well :) – kez Mar 07 '16 at 08:31

2 Answers2

5

In Startup.Auth, reference the RoleManager like this:

    public void ConfigureAuth(IAppBuilder app)
    {
        // Add this reference
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
    }

Make sure your Controller includes this constructor:

        // Include this
        private ApplicationRoleManager _roleManager;
        // You already have this
        public ApplicationRoleManager RoleManager { get { return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); } private set { _roleManager = value; } }

Rebuild, try again and hopefully this will sort it out.

RickL
  • 3,318
  • 10
  • 38
  • 39
  • thanks for your guidance , once I did that my all other tables gone :( – kez Mar 07 '16 at 10:18
  • @kez - I don't understand what you mean by "all other tables gone" ..? – RickL Mar 07 '16 at 10:25
  • it deleted all my tables, remain only ASpNet identity tables, another thing is, once I add new table to this database that consist default aspnet identity tables , then I debug the program its deleting all the newly added tables , and deleted all the data inside in asnet identity tables, how to avoid this – kez Mar 07 '16 at 10:48
  • @kez - adding the lines as indicated will not take out database tables, they just reference the RoleManager. Please check that you didn't just copy and paste ConfigureAuth because (one thing that might cause it) is that it should also include: app.CreatePerOwinContext(ApplicationDbContext.Create); and probably other things. It may also be another problem with your re-build generating your tables if you are using code-first. Please check that you *add* the lines indicated, but leave your other code the same. – RickL Mar 07 '16 at 10:59
  • This solved it for me. Thank you. – Damian Chambers May 27 '22 at 10:57
2

Check your RoleManager.Roles property. Seems that it does not return anything from DB. Also be sure that you have at least one role entity in UserRoles table

Andrew
  • 1,474
  • 4
  • 19
  • 27
  • where I can find that property , in IdentityModel.cs ? – kez Mar 07 '16 at 07:40
  • 1
    @kez Just do a var test = RoleManager.Roles; and debug to see what you get. – andreasnico Mar 07 '16 at 08:14
  • Yep its null ,how to load values then – kez Mar 07 '16 at 08:19
  • @kez, If you really want to get all your roles from database you can use `GetRolesAsync()` method from manager. It return you the same result as using of `Roles` property. – Andrew Mar 07 '16 at 10:31
  • I get the same problem and when i looked into `Identity` code I found that framework tries to return instance of `IQueryable` and this is cause internal error in it – Andrew Mar 07 '16 at 10:33