Link ASP.NET Identity users to user detail table

后端 未结 5 2075
旧巷少年郎
旧巷少年郎 2020-12-29 16:46

I\'ve used default MVC template with individual authorization. After running the application it automatically creates the required Identity tables. I\'ve successfully regist

5条回答
  •  鱼传尺愫
    2020-12-29 17:03

    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 GenerateUserIdentityAsync(UserManager 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(context);
    var manager =  new ApplicationUserManager(store);
    var user = new ApplicationUser() { Email = "email@email.com", UserName = "username", PersonalInformation = new PersonalInformation { FirstName = "FirstName" } };
    manager.Create(user, "Password123!");
    
    // Update user
    var store = new UserStore(context);
    var manager =  new ApplicationUserManager(store);
    var user = manager.Users.FirstOrDefault(u => u.Id == id);
    user.PersonalInformation.FirstName = "EditedName";
    manager.Update(user);
    

提交回复
热议问题