Search code examples
c#asp.net-mvcentity-frameworkasp.net-identity

Get List of custom user class inherit from ApplicationUser in Asp.Net MVC


I created a class that inherits from ApplicationUser like This:

public class Company : ApplicationUser
{
    public string CompanyName { get; set; }
    public String Boss { get; set; }
    public string Slogan{ get; set; }
}

EF will add a Discriminator column to dbo.AspNetUsers

I get a property from Company class like this:

Company cm = (Company)db.Users.Find(id);

That works fine but how can I get a list of Company users (i.e. where Discriminator == "Company")?


Solution

  • You need to use the OfType<...>() extension:

    var companyUsers = db.Users.OfType<Company>();
    

    Doing that will run SQL something like this:

    SELECT
        [Extent1].Id,
        [Extent1].Column2.
        --etc
    FROM [dbo].[AspNetUsers] AS [Extent1]
    WHERE [Extent1].[Discriminator] = Company'