当前位置: 首页 > 编程语言 > C#

链接ASP.NET身份用户到用户详情表分享

时间:2023-04-10 23:24:47 C#

链接ASP.NET身份用户到用户详情表我使用的是默认的MVC模板和个人授权。运行应用程序后,它会自动创建所需的标识表。我已经成功注册了几个用户,都存储在AspNetUser表中。现在我想要的是登录用户可以添加更多信息,如名字、姓氏、地址等。为此,我创建了另一个包含列的表PersonalInformation来存储这些信息。我还在EditProfile中创建了一个EditProfileAction。现在,如何将ASP.NETIdentity用户链接到该表?我应该将Id列作为外键添加到AspNetUser吗?另外,如何将编辑后的信息与登录的用户ID一起成功存储在“PersonalInformation”表中?您可以在用户和配置文件之间创建一对一的关系,然后使用应用程序用户管理器来创建或更新用户。publicclassApplicationUser:IdentityUser{publicasyncTaskGenerateUserIdentityAsync(UserManagermanager){//注意authenticationType必须匹配CookieAuthenticationOptions.AuthenticationTypevaruserIdentity=awaitmanager.CreateIdentityAsync(this,DefaultAuthenticationTypes.ApplicationCookie);//在此处添加自定义用户声明returnuserIdentity;}publicvirtualPersonalInformation{get;放;}}publicclassPersonalInformation{[Key,ForeignKey("User")]publicstringUserId{get;set;}publicstringFirstName{get;放;}//其他字段...publicvirtualApplicationUserUser{get;set;}}//创建用户varstore=newUserStore(context);varmanager=newApplicationUserManager(store);varuser=newApplicationUser(){Email="email@email.com",UserName="username",PersonalInformation=newPersonalInformation{FirstName="FirstName"}};manager.Create(user,"密码123!");//更新用户变量存储e=新用户存储(上下文);varmanager=newApplicationUserManager(store);varuser=manager.Users.FirstOrDefault(u=>u.Id==id);user.PersonalInformation.FirstName="EditedName";经理。更新(用户);身份与数据库接口的方式是通过实体框架自动进行的。在您的解决方案中,应该有一个名为ApplicationDbContext的类,它是实体框架上下文。我个人建议查找一些实体框架指南并弄清楚它如何与身份交互。但快速概述是:要使用实体框架向数据库添加另一个表,您需要向上下文添加一个DbSet。publicDbSetpersonalInformation{get;set;}然后您需要更新ApplicationUser以保存对personalInformation的引用。然后,您需要使用生成的迁移或自动迁移将数据库迁移到最新版本。您之后所做的任何更改都将通过实体框架进行。是的,您应该在表中添加一个外键。如何做到这一点取决于你如何设置实体框架(EDMX/代码优先/数据库逆向工程师),但这个过程在许多其他问题中都有解释。这是一个单独的问题,之前已经回答过,尝试搜索。现在要存储用户的详细信息,您可以在注册此用户时在PersonalInformation表中创建一条记录,或者在编辑用户时检查它是否存在:如果分享的所有内容对您有用,您需要进一步了解C#学习教程,希望大家多多关注——varcurrentUserId=User.Identity.GetUserId();//查找现有记录varpersonalInformation=_dbContext.PersonalInformation.FirstOrDefault(p=>p.UserId==currentUserId);if(personalInformation==null){//如果不存在,创建并附加新记录personalInformation=_dbContext.PersonalInformation.Create();}//将传入的模型属性映射到实体personalInformation.FirstName=model.FirstName;personalInformation.Address=model.Address;//...//添加或更新数据库中的实体_dbContext.SaveChanges();varmanager=newUserManager(newUserStore(newApplicationDbContext()));varstore=newUserStore(newApplicationDbContext());varctx=store.Context;varcurrentUser=manager.FindById(User.Identity.GetUserId());varmanager=newUserManager(新UserStore(新ApplicationDbContext()));varstore=newUserStore(newApplicationDbContext());varctx=store.Context;varcurrentUser=manager.FindById(User.Identity.GetUserId());pedido.Nombre=currentUser.Nombre;整理自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处: