Customizing User's Profile to add new fields in brand new database table
In this post you will learn how to customize User’s Profile and add new fields/properties/columns (FirstName, LastName and EmailID) in a brand new table with ASP.NET Identity System.
In the image given below, look at right Sever Explorer, this is what we are going to achieve, a new table is there by name ‘UserProfileInfo’.
As I mentioned earlier, ASP.NET Identity System uses Entity Framework Code First, so we have opportunity to customize User’s Profile in a way we want. So, I’m going one step further to generate a new database table to store User’s Profile information.
Follow the steps from here.
Step 1: Add new properties in new class ‘UserProfileInfo’
Recall last post, instead of adding new properties in ApplicationUser class, we will create another class UserProfileInfo and place a virtual class field in ApplicationUser class. Also, add a new DbSet in ApplicationDbContext. In the image given below, we can see both formats. For the sake of demo, I will be adding UserProfileInfo in DbContext page but you should keep it separate.
Step 2: Update Account Controller's Register action (Post Version)
In above image, we moved FirstName, LastName and EmailID from ApplicationUser class to a new class, so we need to update Register action also, look at the following code.
Step 3: Add New Migration
Step 3: Add New Migration
Once we done with above steps, bring the Package Manager Console and execute following command.
This command will generate a database script file, now execute following command to run this script file against database.
Now, all the new properties will turn into new database table.
Step 4: Run the Application
Let's go and run the application and try to create new user account. We will see a new database table by name ‘UserProfileInfos’ up and it has user profile information FirstName, LastName and EmailID.
Step 5: Accessing User Profile Data
If user is logged in, we can access user's profile information that we just added following way in the controller.
Or if we want to access these information directly on the view page, here is another way.
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var currentUser = manager.FindById(User.Identity.GetUserId());
Please note I have used all the required namespaces.
In next post, we will explore how to seed these database tables (AspNetUsers, UserProfileInfos) that we just created here, we will seed all the information including UserName, Password, FirstName, LastName, EmailID etc. This is also going to be very interesting and informative.
Hope this helps.