.NET 6带有实体框架核心的单文件ASP.NET模板

发布于 2025-01-18 03:42:46 字数 3030 浏览 3 评论 0原文

我正在使用 Visual Studio 2022/.NET 6 Razor 页面模板。它使用顶级 C# 10 程序文件。 Program.cs 看起来像这样:

using Microsoft.EntityFrameworkCore;
using Data;
using Services;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMemoryCache();
builder.Services.AddRazorPages();

var settings = builder.Configuration.Get<AppSettings>();

builder.Services
    .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

var app = builder.Build();
app.UseHttpsRedirection();
app.UseRouting();
app.MapRazorPages();
app.Run();

我的 DBContext 看起来像这样

public class ApplicationDbContext: DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
    internal DbSet<MyModel> MyModels { get; set; }
    protected override void OnModelCreating(ModelBuilder builder){ /* ... */ }
}

当我运行 dotnet ef migrations add InitialMigration -v 时,我收到以下错误:

Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider in assembly 'Data'...
Finding Microsoft.Extensions.Hosting service provider...
No static method 'CreateHostBuilder(string[])' was found on class 'Program'.
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'ApplicationDbContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
 ---> System.InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Data.DatabaseContext.ApplicationDbContext]' while attempting to activate 'Data.DatabaseContext.ApplicationDbContext'.

Visual Studio Add-Migration 也构建失败,但不提供堆栈跟踪。

提供的链接表明我可以添加 的实现IDesignTimeDbContextFactory 包含一些可能有效的启动代码。

我创建了这个类,但它似乎也没有做任何事情。

public class ApplicationContext: IDesignTimeDbContextFactory<ApplicationDbContext>
{
    ApplicationDbContext IDesignTimeDbContextFactory<SanDiegoContext>.CreateDbContext(string[] args)
    {
        IConfigurationRoot configuration = MyStaticConfigurationBuilder.GetConfig();

        var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
        optionsBuilder.UseSqlServer(connectionString: configuration.GetConnectionString("DefaultConnection"));

        return new ApplicationDbContext(optionsBuilder.Options);
    }
}

是否可以在 .NET 6 中使用 EF Core,而无需构建 GetHostBuilder(string[]) 方法和 Startup 类?如果是这样,我做错了什么?

I am using the Visual Studio 2022/.NET 6 Razor pages template. It uses a top-level C# 10 program file. Program.cs looks something like this:

using Microsoft.EntityFrameworkCore;
using Data;
using Services;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMemoryCache();
builder.Services.AddRazorPages();

var settings = builder.Configuration.Get<AppSettings>();

builder.Services
    .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

var app = builder.Build();
app.UseHttpsRedirection();
app.UseRouting();
app.MapRazorPages();
app.Run();

My DBContext looks like this

public class ApplicationDbContext: DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
    internal DbSet<MyModel> MyModels { get; set; }
    protected override void OnModelCreating(ModelBuilder builder){ /* ... */ }
}

When I run dotnet ef migrations add InitialMigration -v, I get the following error:

Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider in assembly 'Data'...
Finding Microsoft.Extensions.Hosting service provider...
No static method 'CreateHostBuilder(string[])' was found on class 'Program'.
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'ApplicationDbContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
 ---> System.InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Data.DatabaseContext.ApplicationDbContext]' while attempting to activate 'Data.DatabaseContext.ApplicationDbContext'.

Visual Studio Add-Migration also fails to build, but provides no stack trace.

The provided link indicated that I might be able to add an implementation of IDesignTimeDbContextFactory to contain some startup code that might work.

I created this class, but it also seems to do nothing.

public class ApplicationContext: IDesignTimeDbContextFactory<ApplicationDbContext>
{
    ApplicationDbContext IDesignTimeDbContextFactory<SanDiegoContext>.CreateDbContext(string[] args)
    {
        IConfigurationRoot configuration = MyStaticConfigurationBuilder.GetConfig();

        var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
        optionsBuilder.UseSqlServer(connectionString: configuration.GetConnectionString("DefaultConnection"));

        return new ApplicationDbContext(optionsBuilder.Options);
    }
}

Is it possible to use EF Core in .NET 6 without building a GetHostBuilder(string[]) method and a Startup class? If so, what am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

万人眼中万个我 2025-01-25 03:42:46

我通过以下步骤使其工作:

  1. 重建项目。
  2. 确保我在正确的项目中使用 Visual Studio 命令行工具
  3. Microsoft.EntityFrameworkCore.Design 安装到我的 Web 项目
  4. 确保我的项目使用标准 CTRL-B 自行构建code> 或 dotnet build

然后我的启动看起来像这样:

using Microsoft.EntityFrameworkCore;
using Data;
using Services;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMemoryCache();
builder.Services.AddRazorPages();

var settings = builder.Configuration.Get<AppSettings>();

builder.Services
    .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

var app = builder.Build();
app.UseHttpsRedirection();
app.UseRouting();
app.MapRazorPages();
app.Run();

并且迁移尝试照常搭建脚手架

I made it work with the following steps:

  1. Rebuild the project.
  2. Make sure I was using Visual Studio Command Line Tools with the right project
  3. Install Microsoft.EntityFrameworkCore.Design to my Web project
  4. Make sure my project builds on its own with a standard CTRL-B or dotnet build

Then my startup looks like this:

using Microsoft.EntityFrameworkCore;
using Data;
using Services;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMemoryCache();
builder.Services.AddRazorPages();

var settings = builder.Configuration.Get<AppSettings>();

builder.Services
    .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

var app = builder.Build();
app.UseHttpsRedirection();
app.UseRouting();
app.MapRazorPages();
app.Run();

and the migration attempts to scaffold as usual

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文