简体   繁体   中英

How to extend User Identity with an IEnumerable/Collection property

Similar to this question: How to extend available properties of User.Identity

When a user logs in I'd like to load the departments my user has an association with. I'm guessing that I'd add a property to the ApplicationUser class like this:

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; }
    }

My question is how/where would I populate the collection, and then how would I access the property later in my controllers. From what I understand, claims would be OK for simple types - an Id for example - but can they be used with collections?

I'm assuming once I have this property loaded, I'd be able to query the collection without hitting the database each time I need this information about the user - which will be often.

Any help appreciated.

First of all, create the collection entity, ie Department. Then reference the Id of the ApplicationUser entity within that.

Assuming you use entity framework code-first, here is an example:

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()
    {

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM