.NET Core: "Unable to materialize entity instance of type 'IdentityUser'. No discriminators matched the discriminator value"

Viewed 4138

I'm creating a Profile for a user, adding columns to ApplicationUser and then executing the DbSet command at ApplicationDbContext. Just writing the DbSet command, it will throw an error:

InvalidOperationException: Unable to materialize entity instance of type 'IdentityUser'. No discriminators matched the discriminator value ''.

What did I do wrong and where? How can I fix it? Just dropping DbSet at ApplicationDbContex, everything can run normally.

Enter image description here

Code of the ApplicationUser:

public class ApplicationUser : IdentityUser
{
    [Display(Name = "Full Name")] public string FullName { get; set; }
    public DateTime CreateAt { get; set; }
    public DateTime? UpdateAt { get; set; }
    public string ImagePath { get; set; }

    public ApplicationUser()
    {
        CreateAt = DateTime.Now;
        UpdateAt = DateTime.Now;
    }
}

The ApplicationDbConText:

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

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

It seems that you're missing the ApplicationUser as a generic argument for your context.

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>

See more in detail: Customize identity model

I don't know if this will help at all. I just tried creating an extension table for IdentityUsers after having created a test user in the database; ran into this error, and when I checked the database it added a Discriminator attribute to the IdentityUser table. So for my test user I put "IdentityUser" in as the discriminator and it loaded the page up perfectly fine. It might be because that user was logged in and it couldn't load the default unlogged in page, but figured I would throw that out there.

My assumption is that it was trying to load the user, but it didn't know how to handle a blank discriminator spot and it doesn't assign a default discriminator value to previously created users.

In your Startup.cs or Program.cs (it depends whether you use ASP.NET Core 6.x or earlier).

Change this:

builder.Services.AddDefaultIdentity<IdentityUser>

To this:

builder.Services.AddDefaultIdentity<ApplicationUser>

Do not forget. In addition to modify that in your Shared/_LoginPartial.cshtml:

Those:

@inject SignInManager<IdentityUser> SignInManager

@inject UserManager<IdentityUser> UserManager

To those:

@inject SignInManager<ApplicationUser> SignInManager

@inject UserManager<ApplicationUser> UserManager

Related