Search code examples
c#asp.netasp.net-mvc-4asp.net-identity-2

List of values as a user attribute


I'm using identity 2.1.0 in ASP.NET MVC 5 application, and I have pages for admin to work (create/edit/delete user) with some custom user properties I defined. However I need to store a list of values in one field. How can I achieve this by using identity, and how to show this on a web page ?


Solution

  • To save such values you can extend your ApplicationUser, in case of multiple values you can do this via an n:m relationship:

    First create a table to store the country values in (also add to your DbContext as e.g. public DbSet<Country> Countries { get; set; }):

    public class Country
    {
        [Key]
        public int Id { get; set; } // or e.g. "string Code" to save e.g. "us"
    
        public string Name { get; set; }
    
        public List<ApplicationUsers> Users { get; set; }
    }
    

    then you can also add a list of Country to your ApplicationUser:

    public class ApplicationUser : IdentityUser<KEY>
    {
         // ...
    
         public List<Country> Countries { get; set; }
    }
    

    and finally to update the countries of a user something like the following:

    var user = // get user
    var countryToAdd = db.Countries.FirstOrDefault(c => c.Name == countryName) ??
                           new Country() { Name = countryName };
    if (user.Countries == null)
        user.Countries = new List<Country>() { countryToAdd };
    else if (!user.Countries.Contains(countryToAdd))
        user.Countries.Add(countryToAdd);
    
    db.SaveChanges();
    

    And to get all users from one country:

    var country = db.Countries.Include(c => c.Users)
                    .FirstOrDefault(c => c.Name == countryName);
    if (country != null)
    {
        var users = country.Users;
    }