1

I am developing an application in ASP.NET Core 2.1. I am using Identity with built-in user accounts. Now I am trying to develop a user maintenance module in this application where I'm stuck. I am unable to fetch the data inside the controller. Here is my code:

ApplicationDbContext.cs:

public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<ApplicationUser> ApplicationUsers { get; set; }

}

Startup.cs:

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddIdentity<IdentityUser,IdentityRole>(config => {
            config.SignIn.RequireConfirmedEmail = true;
        })
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultUI()
        .AddDefaultTokenProviders();

        services.AddMemoryCache();
        services.AddSession();

        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddSessionStateTempDataProvider();

        services.AddSingleton<IEmailSender, EmailSender>();
    }

ApplicationUser.cs:

public class ApplicationUser : IdentityUser
{
    [Required]
    public string FirstName { get; set; }

    [Required]
    public string Name { get; set; }
}

Index.cshtml:

@model IEnumerable<TestIdentity.Models.ApplicationUser>
@{
    ViewData["Title"] = "Index";
}
<h2>Application users</h2>
@foreach (var item in Model)
{
    <p>@item.Name</p>
}

ApplicationUsersController.cs::

public class ApplicationUsersController : Controller
{
    private readonly ApplicationDbContext _context;

    public ApplicationUsersController(ApplicationDbContext context)
    {
        _context = context;
    }

    // GET: Administrator/ApplicationUsers
    public async Task<IActionResult> Index()
    {
        return View(await _context.ApplicationUsers.ToListAsync());
    }
}

_context.ApplicationUsers.ToListAsync() is not returning any results, although there is data in my AspNetUsers table.

2
  • Can you share your ApplicationDbContext?
    – ipinak
    Dec 17, 2018 at 23:09
  • @ipinak: I added my ApplicationDbContext in the question. FYI: When I change the first line in my ApplicationDbContext from public class ApplicationDbContext : IdentityDbContext to public class ApplicationDbContext : IdentityDbContext<ApplicationUser> it does work, but then my register page is throwing this error: InvalidOperationException: Cannot create a DbSet for 'IdentityUser' because this type is not included in the model for the context. Dec 17, 2018 at 23:18

2 Answers 2

5

If you would like to use custom ApplicationUser for your Identity instead of default IdentityUser.You need to make some changes after declaring the model.

1.In dbContext:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>

2.In startup.cs:

services.AddIdentity<ApplicationUser,IdentityRole>(config => {
        config.SignIn.RequireConfirmedEmail = true;
    })
...

3.In your /Shared/_LoginPartial.cshtml

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
0
0

IdentityUser is not a part of your dbContext. You need to use UserManager<IdentityUser> instead.

Your ApplicationUsersController class should look like this

public class ApplicationUsersController : Controller
{
    private readonly ApplicationDbContext _context;
    private readonly UserManager<IdentityUser> _userManager;

    public ApplicationUsersController(ApplicationDbContext context,
                                      UserManager<IdentityUser> userManager;)
    {
        _context = context;
        _userManager = userManager;
    }

    // GET: Administrator/ApplicationUsers
    public async Task<IActionResult> Index()
    {
        return View(await _userManager.Users.Cast<ApplicationUser>().ToListAsync());
    }
}
5
  • Hi Dusan, thanks for your reply, but that will not work for me: InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List1[Microsoft.AspNetCore.Identity.IdentityUser]', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable1[Cnock.Models.ApplicationUser]'. Dec 17, 2018 at 23:28
  • I added some extra fields to the IdentityUser class. By doing this, the controller is returning an IdentityUser instead of an ApplicationUser. Dec 17, 2018 at 23:30
  • I forgot to cast the list elements to ApplicationUser. Now I fixed the answer, so try now Dec 17, 2018 at 23:33
  • InvalidCastException: Unable to cast object of type 'Microsoft.AspNetCore.Identity.IdentityUser' to type 'Cnock.Models.ApplicationUser'. :-( Dec 17, 2018 at 23:36
  • The problem is that _userManager doesn't load properties of ApplicationUser table and _context doesn't load properties of IdentityUser table. My suggestion is to remove parent class on ApplicationUser and put a property which will act as a foreign key to an IdentityUser. So when you want to use data from IdentityUser use _userManager and when you want to use data from ApplicationUser use _context Dec 17, 2018 at 23:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.