Dear Coder,
Let’s talk about the person who matters the most in our field.
No, it’s not you (though you’re enduringly important to me, dear Coder).
I’m talking about the user.
How Do I Represent the User in Code?
I want the user to have a good user experience, so I build a model that inherits from AspNetCore’s IdentityUser. By doing this, I inherit a set of robust properties without having to write too much new code.
Create User Model and Inherit Properties from IdentityUser
Let’s start with the User model:
In my ToonSpace project, I create a model named “ToonUser” and add some custom properties that IdentityUser doesn’t already cover, including:
FirstName
LastName
DisplayName
FullName
ImageData
ContentType
I also inherit the properties of IdentityUser by using the Microsoft.AspNetCore.Identity namespace and inheriting from Identity user when I name the class:
What properties does IdentityUser grant me access to? A lot.
With these properties appended to my ToonUser, I have the tools I need to allow users to register accounts and interact with my application.
Modify Startup.cs and ApplicationDbContext
In my data folder, I access my ApplicationDbContext file and inherit IdentityDbContext of type ToonUser.
Then I add the ToonUser to my Identity service, along with Default UI and DefaultTokenProviders.
Scaffold Identity Pages
Now I’m ready to scaffold Identity pages for user accounts. I add a Scaffolded Item in my Areas > Identity folder and select “Identity.”
I override all files and select ApplicationDbContext as my data context class. Once I add the scaffolded Identity pages, my Identity folder will be filled with boilerplate razor pages.
I access the code behind for the “register” view and add properties for First Name and Last Name because those properties are not the default with Identity pages. I also add fields to the View for the user to enter this information.
Now that I have registration pages scaffolded and augmented to fit my ToonUser model, users can register an account on my application.
I hope these letters find you well, dearest Coder.
Until next time, godspeed in your keystrokes.
Clickity Clacks,
Kasey
Top comments (1)
Just found this in 2023 and it was exactly what I needed. Thank you! Being unable to create a user class using the default ApplicationDbContext during the scaffolding process was throwing me and I wanted to avoid having a totally separate user db/context.