【问题标题】:How to extend User Identity with an IEnumerable/Collection property如何使用 IEnumerable/Collection 属性扩展用户身份
【发布时间】:2017-02-07 10:33:04
【问题描述】:

类似这个问题:How to extend available properties of User.Identity

当用户登录时,我想加载与我的用户关联的部门。我猜我会像这样向ApplicationUser 类添加一个属性:

public class ApplicationUser : IdentityUser<Guid, GuidUserLogin, GuidUserRole, GuidUserClaim>
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            return userIdentity;
        }


        public IEnumerable<Department> Departments { get; set; }
    }

我的问题是我将如何/在哪里填充集合,然后如何在我的控制器中访问该属性。据我了解,声明对于简单类型(例如 Id)来说是可以的,但它们可以与集合一起使用吗?

我假设一旦我加载了这个属性,我就可以在每次需要有关用户的信息时查询集合而无需访问数据库 - 这很常见。

任何帮助表示赞赏。

【问题讨论】:

  • 也许有一个域实体用于存储集合并引用ApplicationUser的Id来建立关系?
  • 在ApplicationUser类的构造函数中?

标签: c# asp.net-mvc asp.net-identity claims-based-identity


【解决方案1】:

首先,创建集合实体,即部门。然后在其中引用 ApplicationUser 实体的 Id。

假设你使用实体框架代码优先,这里是一个例子:

public class ApplicationUser : IdentityUser<Guid, GuidUserLogin, GuidUserRole, GuidUserClaim>
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            return userIdentity;
        }

        public ApplicationUser()
        {
           Departments = new Collection<Department>();
        }

        public ICollection<Department> Departments { get; set; }
    }



public class Department
{

    public string UserId { get; set; }

    public int DepartmentId { get; set; }

    public ApplicationUser User { get; set; }

    protected Department()
    {

    }

}

【讨论】:

  • 非常感谢 Umut 的回复。我不知道你会在哪里点击 DB 来填充 Departments 集合。
  • 正如我所指出的,如果您使用的是代码优先迁移,您将首先将您的 Department 实体作为 DbSet 类型的属性添加到 DbContext 类中。然后创建并运行迁移。每当您从带有实体框架的数据库中获取用户实例时,将为您填充部门。有关建立关系的更多信息,请查看here
猜你喜欢
  • 2015-04-09
  • 2015-09-01
  • 2020-12-18
  • 2012-01-26
  • 1970-01-01
  • 1970-01-01
  • 2022-09-29
  • 1970-01-01
  • 2023-03-22
相关资源
最近更新 更多