asp.net-mvc - 使用 Entity Framework 向 MVC 5 中的 Identity 添加属性

标签 asp.net-mvc entity-framework asp.net-identity

我正在使用 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/

相关文章:

asp.net-mvc - MVCMailer SendAsync 和删除附件

c# - .NET 4.0、MVC 2、 Entity Framework 4 和存储库模式

entity-framework - 如何让 EF6 遵守关联/关系多样性中的唯一约束(在 FK 上)?

c# - 使用 EF 和 LINQ 按用户对事务进行分组

asp.net-mvc - 如何在asp.net core中处理cookie过期

asp.net-mvc - DRY 与 MVC 和 View 模型的安全性和可维护性

html - mvc razor with @html.actionurl 在数据库中存储 HTML

javascript - 将 mvc 复选框绑定(bind)到 javascript 函数

c# - 如何删除 dbo.AspNetUserClaims 和 dbo.AspNetUserLogins 表(IdentityUserClaim 和 IdentityUserLogin 实体)?

c# - OpenIdConnectAuthenticationHandler : message. 状态为 null 或为空