Search code examples
asp.netasp.net-coredot

.NET querying Aspnetusers instead of Custom AuthUser and Yet AspNetUser does not Exist


I write a custom IdentityUser which is AuthUser.

public class AuthUser : IdentityUser
    {
        public int StudentsId { get; set; }
        public virtual Students StudentProfile { get; set; }

        public int InstructorId { get; set; }
        public virtual Instructor InstructorProfile { get; set; }

        public bool IsStudent { get; set; }
        public bool IsInstructor { get; set; }
    }

The context is okay as you can see

 public class LmsContext : IdentityDbContext<AuthUser> //DbContext
    {
}

The startup.cs is all setup

services.AddDbContext<LmsContext>(options =>
                options.UseSqlServer(
                Configuration.GetConnectionString("UCIPrimarySchool"))
                );
            services.AddDefaultIdentity<AuthUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<LmsContext>();

            services.AddControllersWithViews();
            services.AddRazorPages();

But when I try to login I get the following error.

An unhandled exception occurred while processing the request.
SqlException: Invalid object name 'AspNetUsers'.

Microsoft.Data.SqlClient.SqlCommand+<>c.<ExecuteDbDataReaderAsync>b__169_0(Task<SqlDataReader> result)

Why is is not querying the extended AuthUser but instead goes for the none existing table AspNetUsers?


Solution

  • First, you should clarify your relationship and then migrations and updated the database correctly.

    Change your AuthUser like this:

    public class AuthUser : IdentityUser
    {
        public virtual Students StudentProfile { get; set; }
    
        public virtual Instructor InstructorProfile { get; set; }
    
        public bool IsStudent { get; set; }
        public bool IsInstructor { get; set; }
    }
    

    In your Context:

      public DbSet<Students>  Students { get; set; }
      public DbSet<Instructor> Instructor { get; set; }
    

    Migration and update: enter image description here

    After successfully updating the database, you need to change your View/Shared/_LoginPartial code:

    @inject SignInManager<IdentityUser> SignInManager
    @inject UserManager<IdentityUser> UserManager
    

    to

    @inject SignInManager<AuthUser> SignInManager
    @inject UserManager<AuthUser> UserManager
    

    Then enter image description here enter image description here

    Select your LmsContext Add enter image description here

    Then start your app,and login.