Friday, August 22, 2014

Modify default ApplicationUser class of MVC5 template

Those who are new in default template of MVC5 they may feel uneasy to edit the login and module which is totally auto generated. It is not tough to extend the existing functionality. In this article, we will modify the default model class, we will add our own property, and it will reflect in database.

Prior knowledge .
We know that the MVC 5 default template use code first approach strategy for entity framework. So, to update the mechanism of default template you have to familiar with code first approach.  In this example, I am using VisualStudio 2013, which provides MVC5 template by default. If you are using any other lower version of Visual studio, you have to install template on your own.
Once you open visual studio 2013 and select web tab, you will find the default template.

Click on OK and it will pop up another wizard, which will ask you to select project type. Please select MVC application and individual user account in application. Selection of individual user account is needed to scaffold the application with proper code of authentication.
Once the application get create, you should see the below project structure. In MVC5 default template, we will see two classes.
They are AccountViewModel and IdentityModels. The AccountViewModel.cs file contains default model that is related to login module and IdentityModule.cs file contain the code related to data access mechanism using Entity Framework.
To edit the default login modul , we have to modify both classes. So, let’s open AccountViewModel at first. In this file you will find RegisterViewModel class which contains username , password and confirm password fields. Our aim to add another field called “Age” in this model and save value of the property in database. Here is the modified model.
public class RegisterViewModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required(ErrorMessage = "Please enter age")]
        [Display(Name = "Age")]
        public int Age { get; set; }

       
        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

 Now, let’s open IdentityModule.cs file and update like below.  As we have added Age property in model we have to add same property in ApplicationUser class.  In below the applicationDbContext class is defined for Entity Framework configuration.
using Microsoft.AspNet.Identity.EntityFramework;
using System.Data.Entity;

namespace MVC.Models
{
   
    public class ApplicationUser : IdentityUser
    {
        public int Age { get; set; }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }

    }
}
The default constructor is taking the connection string called “DefaultConnection” which has defined in web.config file of the application. Please make sure that the connection string is pointing to right database and database server.  Please make sure that the VisualStudio is running in Administrator mode it needs to create database in DB server.
Hope the connection string setup is all fine , now let’s open AccountController and we will modify Register method as below.


Please have a look on highlighted portion. We are setting the Age property in time of object creation of ApplicationUser class. That is all and nothing to do much here.
Now, open Register.cshtml view from Account folder under view and add Age property to it. It will render age property in page. Here is the sample code.

We have completed the configuration part and now we will migrate database. As this is code first approach , we have to migrate database and then model change will reflect to database. Just run the below command in package manager console.

enable-migrations
This command will enable migration in application. You will find that Migration folder has created in application automatically.

add-migration <migration name>
This command will generate migration code in application according to current model state.

update-database
The command will reflect current model in database. You will find that the Age property has created just like below in AspNetUser table in DB server.


Moreover, that is all about configuration. Let’s run the application and navigate to register link. We will see that the default template has modified and Age field has added as like below.

Once we click on Register button the data should save in AspNetUser table just like below.

We are seeing that Age field has created and data is saving in the field.

Conclusion:-
 In this article we have learned to edit and update the Existing login module of MVC5 application. At first time it’s really little confusing to figure out the implementation and extensibility point but once you understand it’s easy and smooth.



2 comments:

  1. Now how do you update the age for the user in case they did a typo after they registered?

    ReplyDelete
  2. The update process is different flow, We have to provide mechanism for that which I did not discuss here.

    ReplyDelete