Add foreign key to AspNetUser table

跟風遠走 提交于 2020-01-11 14:48:12

问题


I've created an ASP.NET Core Razor Pages application with user identities.

The created project includes a migration that adds all the user tables, such as AspNetUser and AspNetRoles. However, it doesn't create any code models for these tables.

Now I've created my own entity models and I would like some of them to have foreign keys to the AspNetUser table.

How can I do this? Does the platform expose these as classes anyplace? Do I need to manually create models and try to get them to exactly match the tables? Or for that matter, how do I access all of a user's details?


回答1:


The default identity uses IdentityUser, it is not exposed to the project code but you can create a new user model (e.g. AppUser) that is derived from IdentityUser, then add the foreign keys to the new user model:

public class AppUser : IdentityUser
{
    public int AddressId { get; set; }
    public UserAddress Address { get; set; }
}

public class UserAddress
{
    public int Id { get; set; }

    // ...

    public string UserId { get; set; }
    public AppUser User { get; set; }
}

Then replace IdentityUser in startup with AppUser :

services.AddDefaultIdentity<AppUser>();

Then create new migrations to create the new user table.



来源:https://stackoverflow.com/questions/58654074/add-foreign-key-to-aspnetuser-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!