【问题标题】:ASP.NET Identity Table Generation And Project DecouplingASP.NET 标识表生成和项目解耦
【发布时间】:2024-01-18 20:52:01
【问题描述】:

带有实体框架的 ASP.NET Identity OWIN 将以下表添加到数据库中:

ASPNetUsers
ASPNeRoles
ASPNeTokens
ASPNetUserClaims
ASPNetUserLogins
ASPNetUserManagements
ASPNetUserRoles
ASPNetUserSecrets
  1. 谁能解释一下这些名字的来源?我搜索了我的解决方案和项目文件,但没有看到对它们的引用。这些名称是否可自定义(我的意思是它们在生成时——而不是在它们存在于数据库中之后)?

  2. 我尝试了一个实验,并在我的 ASP.NET MVC 5 解决方案中添加了一个新项目。然后我使用 NuGet 安装 Microsoft ASP.NET Identity Owin。然后,我将 Entity Framework 6 添加到该项目中,并创建了一个继承自 DbContext 的数据上下文类。那时,我从包管理器控制台运行了“启用迁移”命令。这创建了一个 Migrations 文件夹和一个迁移类以及一个 Configuration.cs 类。到现在为止还挺好。但是当我运行“add-migration initial”命令时,上面提到的 ASP.NET Identity 表都没有生成。

    然而,当我在 MVC 项目中遵循相同的步骤时, add-migration 命令确实会生成上述表格。在我的 MVC 中 项目,在我的 App_Start 文件夹中有一个 startup.auth.cs 类, 然而。这似乎是关键,但我只是不确定,因为 有些事情是“自动神奇地”发生的,我显然没有 理解。 startup.auth.cs 文件如下所示:

.

using Microsoft.AspNet.Identity;    
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;

namespace AspNetIdentity
{
    public partial class Startup
    {
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
        }
    }
}

如果我希望能够从 MVC 项目以外的项目迁移 ASP.NET 标识表,我该怎么做?

【问题讨论】:

  • 我不敢苟同:询问如何更改表名与询问这些名称来自/起源的问题不同。此外,我的问题涉及到关于解耦的问题,这与所引用的问题不重复。
  • 答案可能很微妙,但答案是让您覆盖 System.Data.Entity.DbModelBuilder 实体。我认为可以推断默认表名驻留在那里。可以使用反编译器来确认
  • 我问的是“它们在哪里”——而不是“我如何使用反编译器对 Microsoft 的代码进行逆向工程并弄清楚发生了什么”。因此,我不认为这是对我问题的回答。

标签: entity-framework migration asp.net-mvc-5 asp.net-identity


【解决方案1】:

注意:这些表名看起来来自 Identity 1.0 的预发布版本,但简短的回答是,它们来自 IdentityDbContext.OnModelCreating,它指定了各种实体的表名。

您的 IdentityDbContext 通常被传递到 UserStore。无论您在哪里创建 UserManager,都可能在哪里同时构建 UserStore 和 IdentityDbContext。请注意,UserStore 的默认构造函数会创建一个使用“DefaultConnection”字符串的新 IdentityDbContext,因此这可能是您没有看到的神奇步骤。

IdentityDbContext

    protected override void OnModelCreating(DbModelBuilder modelBuilder)

【讨论】: