I assume that you are using the standard Identity EF repository implementation.
Identity is very flexible and can be bent into many forms to suit your needs.
If you are looking for a simple relationship between parents and children, where each user will have a parent record (for example, a company), one way to implement this is to add a company link to the user class:
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.AspNet.Identity.EntityFramework; public class ApplicationUser : IdentityUser { public ApplicationUser() { } [ForeignKey("CompanyId")] public Company Company { get; set; } public int CompanyId { get; set; } } public class Company { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int CompanyId { get; set; } public String Name { get; set; } public virtual ICollection<ApplicationUser> Users { get; set; } }
This will entail a foreign key for company users. But from here the next course of action depends on what is required in your application. I would suggest that you will have some kind of restriction for users depending on which company they belong to. For a quick company search, you can store CompanyId in the application at the user's login.
The default implementation of ApplicationUser has the GenerateUserIdentityAsync method. You can change this as follows:
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 identity.AddClaim(new Claim("CompanyId", CompanyId.ToString())); return userIdentity; }
Then, for each request, you can access this CompanyId request from a cookie:
public static int GetCompanyId(this IPrincipal principal) { var claimsPrincipal = principal as ClaimsPrincipal; //TODO check if claims principal is not null var companyIdString = claimsPrincipal.Claims.FirstOrDefault(c => c.Type == "CompanyId"); //TODO check if the string is not null var companyId = int.Parse(companyIdString); //TODO this possibly can explode. Do some validation return companyId; }
And then you can call this extension method from almost any web application: HttpContext.Current.User.GetCompanyId()
source share