我正在使用 MVC 5 和 EF 6 (Datafirst),使用 msssql Management Studio。
我创建了一个新的 mvc 项目,其中包含内置数据库(AspNetUsers 等)
我还创建了一个名为 UserDetails 的新表,其目的是通过 ID 包含有关用户的更多详细信息(因此我在 AspNetUsers id 列到 UserDetails UserId 列之间创建了一个链接)
因此我添加了以下代码
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
userIdentity.AddClaim(new Claim("FirstName", FirstName.ToString()));
return userIdentity;
}
//Extended Propeties
public string FirstName { get; set; }
}
但是当然不行,我在网上查了4个多小时了,有人可以指导我吗?我是 MVC 的新手,一切似乎都很复杂。 我还有以下静态方法:
public static class IdentityExtensions
{
public static string GetFirstName(this IIdentity identity)
{
var claim = ((ClaimsIdentity)identity).FindFirst("FirstName");
// Test for null to avoid issues during local testing
return (claim != null) ? claim.Value : string.Empty;
}
}
为了将其获取到 View 中并显示它.. 我的目标是根据 AspNetUsers 的 1-1 连接在 View 中显示另一个表 (UserDetails) 的数据 (UserDetails.UserId == AspNetUsers.Id)
最佳答案
您所要做的就是扩展 IdentityUser 类,然后添加自定义属性,例如 FirstName 等。然后,由于您首先使用 EntityFramework 数据库,因此您需要在包管理器控制台中使用此命令启用迁移 enable -migrations
,然后添加一个初始迁移,如 add-migration initialMigration
,之后使用此命令 update-database
使用迁移更新数据库,AspNetUsers 表位于您的数据库现在将包含您添加的新列。使用迁移使数据库与模型保持同步
关于asp.net-mvc - 使用 Entity Framework 向 MVC 5 中的 Identity 添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41322413/