ASP.NET Identity. Part 2 – Customizing Entities

ASP.NET Identity gives a class ApplicationUser for storing data about users. It has a lot of properties defined in base class IdentityUser, such as Id, UserName, Email, PhoneNumber, etc. But when you need to add some extra properties, it becomes more complicated.

Entity Framework creates a database only once at first use. It does not recreate, nor modify it. We should use EF migrations to add new fields. Also it gives the possibility to change table names.

1. Add new properties in file Models\IdentityModels.cs

2. Open Package Manager Console and run command

EF will create folder Migrations and a couple of files: Configuration.cs and <timestamp>_InitialCreate.cs with code to create a default database structure.
3. Create new migration and give it a name

Visual Studio will open a file with two method to add and drop columns defined in step 1.
4. Apply EF migration to database.

Now I have the following database structure:

5. I want to enter first and last names during the registration process. So I’ll add two properties to class RegisterViewModel in file Models\AccountViewModels.cs

6. Add code to Views\Account\Register.cshtml file to display these them.

7. Change Register method in Account controller (file Controllers\AccountController.cs) to store them.

8. Also I want to display user’s first name on the top bar of the web application instead of his/her email. To do this we need to modify file Views\Shared\_LoginPartial.cshtml to get ApplicationUser via current user’s Id with the help of Owin context, then to show property FirstName. The final code looks like this:

Leave a Reply

Your email address will not be published. Required fields are marked *