将外键添加到AspNetUser表 [英] Add foreign key to AspNetUser table

查看:75
本文介绍了将外键添加到AspNetUser表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了具有用户身份的ASP.NET Core Razor Pages应用程序.

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

创建的项目包括一个迁移,该迁移添加了所有用户表,例如AspNetUserAspNetRoles.但是,它不会为这些表创建任何代码模型.

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.

现在,我已经创建了自己的实体模型,我希望其中一些具有AspNetUser表的外键.

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?

推荐答案

默认身份使用IdentityUser,它不公开给项目代码,但是您可以创建派生的新用户模型(例如AppUser)从IdentityUser中,然后将外键添加到新的用户模型中:

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; }
}

然后在启动时将IdentityUser替换为AppUser:

Then replace IdentityUser in startup with AppUser :

services.AddDefaultIdentity<AppUser>();

然后创建新迁移以创建新的用户表.

Then create new migrations to create the new user table.

这篇关于将外键添加到AspNetUser表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆