I start to develop an web application with .net core 2 and web service..
when a user registers on the site, he can choose whether he is a company or a simple user, so I store the data in a specific table but the login data are stored in AspNetUsers.
How can i handle it with Identity in .net core?
Simply inherit from ApplicationUser
, i.e.:
public class CompanyUser : ApplicationUser {}
public class SimpleUser : ApplicationUser {}
By default, EF will implement inheritance via STI (single-table inheritance). Essentially, all properties on ApplicationUser
and all derivations will all go into the table for ApplicationUser
(i.e. AspNetUsers
). A Discriminator
column will be added that will house the name of the actual class that was saved. EF will then use this to instantiate the right type when querying. The one downside to this approach is that properties on derived classes must be nullable, since not every type of use would be able to provide values for properties on other user types.
If you prefer, you can implement TPT or table per type. That will give you the standard table for ApplicationUser
with columns for all common properties and a table for each derived type, containing only properties defined on that derived type and a foreign key back to the table for ApplicationUser
. With this approach, you can have non-nullable properties on your derived classes, but querying a user will then require a join. If you want to go this route, you can either add the Table
attribute to the derived class with the name you'd like its table to have, or use the ToTable
fluent config method in OnModelCreating
to do the same.
One thing that you'll need to keep in mind is that generic classes that work with users such as UserManager<TUser>
will need to be instantiate per type you need to work with. For example, even if you do new CompanyUser()
, if you save it via an instance of UserManager<ApplicationUser>
it will be upcast and saved as an instance of ApplicationUser
. To actually save a CompanyUser
instance, you'd need to use an instance of UserManager<CompanyUser>
instead.
If you want to store data of both users in same table use TPH tabel per hierarchy and if you have many column for esch of class use a TPT
Here is the link with a very nice explation
https://www.learnentityframeworkcore.com/inheritance/table-per-hierarchy