I've used default MVC template with individual authorization. After running the application it automatically creates the required Identity tables. I've successfully registered a few users and all of them are stored in the AspNetUser
table.
Now what I want is the logged in user can add more information like first name, last name, address etc. For this I've created another table PersonalInformation
with columns to store this information.
I've also created an EditProfile
Action in the ManageController
.
Now how can I link the ASP.NET Identity user to this table? Should I add an Id
column as a foreign key to AspNetUser
? Also how can I successfully store the edited information in "PersonalInformation" table along with the logged in user id?
You can create one to one relationship between user and personal information and then create or update user using Application User Manager.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
public virtual PersonalInformation PersonalInformation { get; set; }
}
public class PersonalInformation
{
[Key, ForeignKey("User")]
public string UserId { get;set; }
public string FirstName { get; set; }
// other fields...
public virtual ApplicationUser User { get;set; }
}
// Create user
var store = new UserStore<ApplicationUser>(context);
var manager = new ApplicationUserManager(store);
var user = new ApplicationUser() { Email = "[email protected]", UserName = "username", PersonalInformation = new PersonalInformation { FirstName = "FirstName" } };
manager.Create(user, "Password123!");
// Update user
var store = new UserStore<ApplicationUser>(context);
var manager = new ApplicationUserManager(store);
var user = manager.Users.FirstOrDefault(u => u.Id == id);
user.PersonalInformation.FirstName = "EditedName";
manager.Update(user);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With