How to create two type of users with identity and .net core 2

后端 未结 2 1598
执笔经年
执笔经年 2021-01-16 03:18

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, s

2条回答
  •  一生所求
    2021-01-16 04:16

    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 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 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 instead.

提交回复
热议问题