c# – 将ASP.NET Identity用户链接到用户详细信息表

我使用了默认的MVC模板和个人授权.运行应用程序后,它会自动创建所需的标识表.我已成功注册了几个用户,所有用户都存储在AspNetUser表中.

现在我想要的是登录用户可以添加更多信息,如名字,姓氏,地址等.为此,我创建了另一个表PersonalInformation,其中包含用于存储此信息的列.

我还在ManageController中创建了一个EditProfile Action.

现在,我如何将ASP.NET Identity用户链接到此表?我应该将Id列添加为AspNetUser的外键吗?另外,如何将编辑后的信息与登录的用户ID一起成功存储在“PersonalInformation”表中?

最佳答案
您可以在用户和个人信息之间创建一对一关系,然后使用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@email.com", 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);

转载注明原文:c# – 将ASP.NET Identity用户链接到用户详细信息表 - 代码日志