【问题标题】:Add property to Identity in MVC 5, using Entity framework使用实体框架向 MVC 5 中的 Identity 添加属性
【发布时间】:2025-12-18 11:45:01
【问题描述】:

我正在使用 MVC 5 和 EF 6 (Datafirst),使用 msssql 管理工作室。

我创建了一个新的 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;
    }
}

为了在视图中获取并显示它.. 我的目标是根据来自 AspNetUsers (UserDetails.UserId == AspNetUsers.Id) 的 1-1 连接在视图中显示另一个表 (UserDetails) 中的数据

【问题讨论】:

  • 如果您在 ApplicationUser 类中添加属性,它应该可以正常工作......有什么问题??添加该属性后,您是否更新了数据库? ....
  • @DaniyalAwan “自从创建数据库以来,支持 'ApplicationDbContext' 上下文的模型已更改。请考虑使用 Code First 迁移来更新数据库”当我尝试登录时,这是因为它尝试获取名字但它在 AspNetUsers 中不存在,它在 UserDetails 中..
  • 不,您在 applicationUser 中创建了 firstName,而不是在 UserDetails 中,所以它怎么可能在 UserDetails 中。我认为问题是您已经创建了名字但没有更新数据库...使用迁移来更新数据库
  • @DaniyalAwan 我有 2 个表,AspNetUsers 和 UserDetails,我先做了数据库,现在我在这两个表中都有键,我连接了这些键。我想从 User.Identity 访问 UserDetails 中的字段,我该怎么做?我应该做什么?我更新了身份模型以尝试实现这一目标,但没有成功..
  • 这是一篇题为“在 VS 2013 模板中自定义 ASP.NET Identity 中的配置文件信息”blogs.msdn.microsoft.com/webdev/2013/10/16/… 的博文,看起来非常有用。

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


【解决方案1】:

您所要做的就是扩展 IdentityUser 类,然后添加您的自定义属性,如 FirstName 等。然后由于您首先使用 EntityFramework 数据库,您需要在包管理器控制台enable-migrations 中使用此命令启用迁移,然后添加一个初始迁移,如add-migration initialMigration,然后使用此命令update-database 使用迁移更新数据库,数据库中的 AspNetUsers 表现在将包含您添加的新列。使用迁移使您的数据库与模型保持同步

【讨论】:

    【解决方案2】:

    如果两个表之间存在正确连接,您可以使用Eagerly Loading 从另一个实体获取一个实体的详细信息。

    【讨论】: