“尚未为此 DbContext 配置数据库提供程序”Entity Framework Core

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

我正在使用带有 Discord.NET 的独立 Entity Framework Core。我创建了一个

DbContext
并将其作为服务添加到我的程序入口点中。

由于某种原因,每当我尝试创建迁移时,我都会收到此错误,但我无法弄清楚是什么原因导致的。

dotnet ef migrations add Initial 

错误:

无法创建类型为“”的“DbContext”。异常“尚未为此 DbContext 配置数据库提供程序。”

可以通过重写“DbContext.OnConfiguring”方法或使用“AddDbContext”来配置提供程序 应用服务提供商。

如果使用“AddDbContext”,则还要确保您的 DbContext 类型在其构造函数中接受 DbContextOptions 对象,并将其传递给 DbContext 的基本构造函数。尝试创建实例时抛出。

有关设计时支持的不同模式,请参阅

https://go.microsoft.com/fwlink/?linkid=851728

/DataContext.cs


using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore; namespace Boolean; public class DataContext : DbContext { public DataContext() { } public DataContext(DbContextOptions<DbContext> options) : base(options) {} public DbSet<Server> Servers { get; set; } } [Table("servers")] public class Server { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("id")] public UInt64 Id { get; set; } [Column("snowflake")] public UInt64 Snowflake { get; set; } }

/Program.cs


using System.Reflection; using Discord; using Discord.Interactions; using Discord.WebSocket; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Boolean; class Program { private static Config _config; static IServiceProvider ConfigureServices() { return new ServiceCollection() .AddSingleton(_config) .AddDbContext<DataContext>(options => options.UseNpgsql(_config.GetConnectionString())) .BuildServiceProvider(); } public static async Task Main() { _config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build().Get<Config>() ?? throw new Exception("Failed to load appsettings.json. Please refer to the README.md for instructions."); _serviceProvider = ConfigureServices(); await Task.Delay(Timeout.Infinite); } }
删除 

public DataContext() { }

 方法重载会导致:

无法解析类型“Microsoft.EntityFrameworkCore.DbContextOptions`1[Microsoft.EntityFrameworkCore.DbContext]”的服务

提前致谢。

c# entity-framework-core entity-framework-migrations
1个回答
0
投票
您只创建了 DI,但在运行时 .NET 无法使用它,因为没有正确设置它,通常,我们需要将 DI 嵌入到运行时,以便运行时可以使用它来使用其构造函数实例化类。

在一个非常简单的版本中,这应该适用于添加迁移:

class Program { public static async Task Main() { var builder = Host.CreateApplicationBuilder(); var configs = builder.Configuration; builder.Services.AddDbContext<DataContext>(options => { options.UseNpgsql(configs.GetConnectionString("connectionName")); }); var app = builder.Build(); await app.RunAsync(); } }

Host

位于
Microsoft.Extensions.Hosting
命名空间中,因此请确保安装Nuget包。

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