1

I am building an app using ASP.Net MVC 5 framework with a database code approach. I need to add custom fields to my Users Table. What is the best way to add custom attributes and access them later? Here is what I have done so far

  1. Logged into SQL Server and added the column to the AspNetUsers table.
  2. I created a new class which ApplicationUser like myUser class below.

    public class User : ApplicationUser
            {
                public int UserId { get; set; }
                public int CampId { get; set; }
            }
    

Additionally, I tried adding my custom attributes to the ApplicationUser directly like the insstruction found on the answer in another question, but I get the following error

 The model backing the 'ApplicationDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269). 

What is the best way to add column to my AspNetUsers table?

Also, How can I access these field from the controller using the Authorized user?

Community
  • 1
  • 1
Junior
  • 11,602
  • 27
  • 106
  • 212

1 Answers1

1

You have to use code-first migrations.

In VS go to Package Manager Console and type:

enable-migrations

then you can add properties to your ApplicationUser class like Birthday or whatever.

Then go back to Package Manager Console and run:

Add-Migration aNameForYourMigration

So for example if you've added a Birthday property you would perhaps name it BirthdaypropertyAddedMigration or whatever makes sense to you.

Then run:

Update-Database

now all your changes to the ApplicationUser class will be persisted to the database.

But if you do the database approach, you have to add the new fields to the users table and then call update model, to regenerate the code.

Legends
  • 21,202
  • 16
  • 97
  • 123