Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Link ASP.NET Identity users to user detail table

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?

like image 227
Umer Waqar Avatar asked Oct 18 '15 11:10

Umer Waqar


1 Answers

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);
like image 193
Gedao Avatar answered Oct 16 '22 17:10

Gedao