我正在使用带有 Discord.NET 的独立 Entity Framework Core。我创建了一个
DbContext
并将其作为服务添加到我的程序入口点中。
由于某种原因,每当我尝试创建迁移时,我都会收到此错误,但我无法弄清楚是什么原因导致的。
dotnet ef migrations add Initial
错误:
无法创建类型为“”的“DbContext”。异常“尚未为此 DbContext 配置数据库提供程序。”
可以通过重写“DbContext.OnConfiguring”方法或使用“AddDbContext”来配置提供程序 应用服务提供商。如果使用“AddDbContext”,则还要确保您的 DbContext 类型在其构造函数中接受 DbContextOptions 对象,并将其传递给 DbContext 的基本构造函数。尝试创建实例时抛出。
有关设计时支持的不同模式,请参阅
/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]”的服务提前致谢。
在一个非常简单的版本中,这应该适用于添加迁移:
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包。