Ume*_*qar 4 c# asp.net-mvc asp.net-mvc-4
我使用了默认的MVC模板和个人授权.运行应用程序后,它会自动创建所需的标识表.我已成功注册了几个用户,所有用户都存储在AspNetUser表中.
现在我想要的是登录用户可以添加更多信息,如名字,姓氏,地址等.为此,我创建了另一个表,PersonalInformation其中包含用于存储此信息的列.
我也在中创建了一个EditProfileAction ManageController.
现在,我如何将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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11572 次 |
| 最近记录: |