问题
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