.NET 6 - 在现有数据表上创建标识上下文

.NET 6 - Create Identity Context on Existing Datatabse

提问人:Milacay 提问时间:11/15/2023 最后编辑:marc_sMilacay 更新时间:11/15/2023 访问量:45

问:

我是 .NET 的新手,正在学习如何创建标识和登录页面。我有用于测试的数据库上下文,它已经有几个表。Database1DbContext

我按照教程添加了 、IdentityUser、IdentityRole......在。需要继承,我不确定如何重用现有的,所以我最终创建了另一个builder.Services.AddIdentityPrograms.csDbContextIdentityDbContextpublic class Database1DbContext : DbContext

public class IdentityDatabase1DbContext : IdentityDbContext

它指向相同的数据库连接(请参阅下面的代码)。

以下是文件中的代码:DbContext.cs

public class Database1DbContext : DbContext
{
    public Database1DbContext(DbContextOptions<Database1DbContext> options) : base(options)
    {
    }

    public DbSet<TransactionModel> Transactions { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

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

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }
}

以下代码位于文件中:Program.cs

builder.Services.AddDbContext<Database1DbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("ConnDatabase1")));

builder.Services.AddDbContext<IdentityDatabase1DbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("ConnDatabase1")));
    
    
// For Identity
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
    .AddEntityFrameworkStores<IdentityDatabase1DbContext>()
    .AddDefaultTokenProviders();

// Adding Authentication
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
});

我做了,它创造了,......桌子,一切都很好。add-migrationupdate-databaseAspNetUsersAspNetRoles

但是,我这样做的方式似乎是重复/低效的,因为我在多个地方创建了重复的上下文和条目。

有没有办法让两者都继承,或者以某种方式使其更有效率?Database1DbContextDbContextIdentityDbContext

提前致谢。

asp.net-core-mvc net-6.0

评论

1赞 Denis Micheal 11/15/2023
有没有办法让 Database1DbContext 同时继承 DbContext 和 IdentityDbContext -> 已经是它的子类,所以通过让你的上下文继承,你也继承了.IdentityDbContextDbContextIdentityDbContextDbContext

答:

1赞 ZNAXNOR 11/15/2023 #1

你的代码将是-DbContext.cs

public class Database1DbContext: IdentityDbContext<IdentityUser>
{
    public Database1DbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {

    }

    public DbSet<TransactionModel> Transactions { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

文件中的代码将是-Program.cs

// Identity
builder.Services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<Database1DbContext>().AddDefaultTokenProviders();