0

我正在关注这个 ASP.NET Core 5 + SQL Server 教程,但使用的是 ASP.NET Core 6 + Sqlite。该教程说我应该add-migration Initial在包管理器中运行,但如果我这样做,我会得到

无法创建“ApplicationDbContext”类型的对象。有关设计时支持的不同模式,请参阅https://go.microsoft.com/fwlink/?linkid=851728

我在网上搜索并找到了这个答案,它说我应该使用传统的命名空间/类/static Main()结构而不是“顶级代码功能”。Program.cs但这是Visual Studio 2022 为项目生成的默认代码。

荒谬的是,我必须更改 MS 创建的默认项目结构以使用 MS 的数据库框架。如何在不将Program.cs结构更改为旧结构的情况下初始化数据库?

程序.cs

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using WebApplication1.Authentication;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

builder.Services.AddDbContext<ApplicationDbContext>();
builder.Services.AddEntityFrameworkSqlite().AddDbContext<ApplicationDbContext>();

builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

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

ApplicationDbContext.cs

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace WebApplication1.Authentication
{
    public class ApplicationDbContext:IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlite(@"Data source=test.db");
        }
    }
}
4

0 回答 0