Adding columns to Membership table. But cannot access them? ASP.NET C#
I have the defa开发者_Go百科ult membership table that was added automatically, then just used server explorer to add more columns, like FirstName
, LastName
, etc. In my code I can access all the default columns, but not the ones I created. Any thing special I need to do?
Here is how I access the table. using user.
gives me all columns, but the one I created.
string userName = User.Identity.Name;
MembershipUser user = (MembershipUser)System.Web.Security.Membership.GetUser(userName).ProviderUserKey;
The reason you are not able to do that is because MembershipUser doesn't expose those properties. You will have to extend that class in order to do that and lot more which will be a lot of work. Also I wouldn't recommend modifying the existing membership tables.
You have two options:
1: Use built-in asp.net profiles as mentioned by Derek Beattie. or
2: Create a separate table to store additional user details. Here's how you do that:
Store-Additional Information
Custom Table
In case if you want to go long route here is how to extend existing membership API.
I believe you have to do that via custom profile fields. http://www.mitchelsellers.com/blogs/articletype/articleview/articleid/9/adding-custom-profile-fields.aspx
To add a new column named "FirstName":
Step 1: Models/IdentityModels.cs
Add the following code to the "ApplicationUser" class:
public string FirstName { get; set; }
Step 2: Models/AccountViewModels.cs
Add the following code to the "RegisterViewModel" class:
public string FirstName { get; set; }
Step 3: Views/Register.cshtml
Add FirstName input textbox to the view:
<div class="form-group">
@Html.LabelFor(m => m.FirstName, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.FirstName, new { @class = "form-control" })
</div>
</div>
Step 4 :
Go to Tools > NuGet Manager > Package Manager Console
Step A : Type “Enable-Migrations” and press enter
Step B : Type “ Add-Migration "FirstName" ” and press enter
Step C : Type “Update-Database” and press enter
i.e
PM> Enable-Migrations
PM> Add-Migration "FirstName"
PM> Update-Database
Step 5: Controllers/AccountController.cs
Go to Register Action and add "FirstName = model.FirstName" to the ApplicationUser i.e
var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = model.FirstName}
精彩评论