扩展脚手架 DbContext 以使用 IdentityDbContext

问题描述 投票:0回答:1

我正在使用 .NET8 RC2 版本和 EF Core,并使用 dotnet ef dbcontextscaffold 命令搭建了一个现有数据库。

此命令生成实体和 AutoGeneratedDbContext

我知道我可以通过创建一个继承此 DbContext 的类来扩展其功能

public class CustomDbContext : AutoGeneratedDbContext
{
 public CustomDbContext()
 {
 }
 public CustomDbContext(DbContextOptions<AutoGeneratedDbContext> options) : base(options)
 {
 }
}

这没问题,但现在我想使用身份验证,为此我必须添加 IdentityDbContext

现在如果我像这样创建 IdentityDbContext

public class IdentityDbContext(DbContextOptions<IdentityDbContext> options) : IdentityDbContext<AppUser>(options)
{
}

然后我必须再注册一个 DbContext,我认为这不是我应该做的。如果我不注册 IdentityDbContext 那么以下操作将不起作用。

builder.Services.AddIdentityCore<AppUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<IdentityDbContext>()
    .AddSignInManager()
    .AddDefaultTokenProviders();

我知道我无法使用 CustomDbContext 进行多重继承,这就是为什么我有点困惑,不知道下一步该怎么做才能使其成为具有 Identity 的单个 DbContext

entity-framework asp.net-core asp.net-identity .net-8.0
1个回答
0
投票

您可以直接复用

AutoGeneratedDbContext
来扩展更多功能。但这里有一个技巧,你可以尝试以下方法:

  1. 我有一个数据库“test02”包含一个“学生”表
  2. 使用数据库命令生成上下文“Test02Context”
    Scaffold-DbContext "server=192.168.2.68;database=test02;user=mysql1;password=xxxxx" Pomelo.EntityFrameworkCore.MySql -OutputDir Models


    3.在“Test02Context”中,删除“OnModelCreating”“OnModelCreatingPartial”方法。像下面这样:
public partial class Test02Context : DbContext
{
    public Test02Context()
    {
    }

    public Test02Context(DbContextOptions<Test02Context> options)
        : base(options)
    {
    }

    public virtual DbSet<Student> Students { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
        => optionsBuilder.UseMySql("server=192.168.2.68;database=test02;user=mysql1;password=xxxxx", Microsoft.EntityFrameworkCore.ServerVersion.Parse("8.0.32-mysql"));
}

4.使用code-fisrt命令生成第一个迁移文件“initial”

Add-migration initial

5.在“Test02Context”中,将

DbContext
替换为
IdentityDbContext
。并在program.cs中。直接使用这个自动生成的上下文。

 Test02Context : IdentityDbContext
builder.Services.AddIdentityCore<IdentityUser>()
    .AddEntityFrameworkStores<Test02Context>()
    .AddSignInManager()
    .AddDefaultTokenProviders();

5.现在生成第二个迁移

Add-migration second
成功后删除第一个迁移文件。然后
Update-database
我们将直接从第二次迁移开始迁移。 6. 检查数据库,身份表已更新。

© www.soinside.com 2019 - 2024. All rights reserved.