I have sample project for identity customization using
Install-Package Microsoft.AspNet.Identity.Samples -pre
command. But, for this project I have a general ApplicationUser class representing all the users of my application. What if I have different categories of users. For example, I may have Teacher
and Student
entities and data representing both the entities will be different. How can I customize my application to store data for both the entities having all the features of ApplicationUser?
One way that I think is inheriting both the classes from ApplicationUser and then doing appropriate changes in IdentityConfig.cs
and defining Controllers for each of them. Is there any other efficient way of doing this?
What if I want to use the built-in authentication and authorization features but using database first workflow?
First, you want to know how to create "types" of users. The way you would do that is exactly how you expected: inherit from ApplicationUser
. By default, this will result in a single "users" table with an additional Discriminator
column. This column will store the class type that was persisted, i.e. "Teacher", "Student", or "ApplicationUser", and EF will utilize this information to new up the right class for each particular record.
One thing to note with this, though, is that you need to be aware of how UserManager
works, namely that it's a generic class (UserManager<TUser>
). The default AccountController
implementation you have from the sample defines a UserManager
property on the controller which is an instance of UserManager<ApplicationUser>
. If you use this instance with something like Teacher
, it will be upcast to ApplicationUser
. In particular if you were to do something like UserManager.Create(teacher)
, it will actually save an ApplicationUser
, instead (the Discriminator
column's value will be "ApplicationUser", rather than "Teacher"). If you need to work with the derived user types, you'll need to create separate instances of UserManager<Teacher>
and UserManager<Student>
for that purpose.
Next, you want to know if you can use a "database first workflow". To answer that, we need to define exactly what that means. EF has what it calls "Database First" which employs EDMX to represent your database entities. This in particular is incompatible with Identity. However, despite the name, what EF calls "Code First", can work with an existing database just as well as create a new one. In other words, yes, you can use an existing database, if you prefer, but no you cannot use "Database First", in the EF-sense. For more information about using an existing database with Code First, see my post.