0

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 ?

Milan M.
  • 959
  • 3
  • 12
  • 27
  • `However I need to store a list of values in one field.` - Why? Can you give an example? Its hard to help without knowing what you actually want to do... – Christoph Fink Jan 27 '15 at 11:27
  • I have a user with a custom property countries. I this property I want to store one or more countries, so that I can filter web page based on its selection of countries. – Milan M. Jan 27 '15 at 11:37
  • Thats a `n:m` relationship and shouldn't be saved "in one field" - I'll write you an answer with an example... – Christoph Fink Jan 27 '15 at 11:40

1 Answers1

1

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;
}
Christoph Fink
  • 22,727
  • 9
  • 68
  • 113