无法创建类型为“”的“DbContext”。异常“无法解析类型”Microsoft.EntityFrameworkCore.DbContextOptions 的服务

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

我创建了一个 .NET Core 8 控制台应用程序。当我尝试生成迁移时,出现此错误:

错误:无法创建类型为“”的“DbContext”。尝试激活“HealthCheck.Console.Context.SystemHealthContext”时出现异常“无法解析类型“Microsoft.EntityFrameworkCore.DbContextOptions`1[HealthCheck.Console.Context.SystemHealthContext]”的服务。”尝试创建实例时抛出。有关设计时支持的不同模式,请参阅 https://go.microsoft.com/fwlink/?linkid=851728

这是我的

DbContext
课程

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

    public DbSet<ServerMasterInfo> ServerMasterInfo { get; set; }
}

这是我的程序类,其中注册了 mydbcontext

var configuration = new ConfigurationBuilder()
    .SetBasePath(AppContext.BaseDirectory)
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

var services = new ServiceCollection();

var connectionString = configuration.GetConnectionString("DbConnection");


services.AddDbContext<SystemHealthContext>(options =>
    options.UseSqlServer(connectionString));

services.AddTransient<SystemHealthCheck>();
var serviceProvider = services.BuildServiceProvider();
var systemHealthCheck = serviceProvider.GetRequiredService<SystemHealthCheck>();

迁移错误详细信息:

Migration Error Details

提前致谢

c# .net-core entity-framework-core
1个回答
0
投票

您可以尝试在 Dbcontext 中配置连接字符串

    public class SystemHealthContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var configuration = new ConfigurationBuilder()
                .SetBasePath(AppContext.BaseDirectory)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .Build();

            var connectionString = configuration.GetConnectionString("DbConnection");
            optionsBuilder.UseSqlServer(connectionString);
        }

        public DbSet<ServerMasterInfo> ServerMasterInfo { get; set; }
    }

然后在program.cs中

services.AddDbContext<SystemHealthContext>();
© www.soinside.com 2019 - 2024. All rights reserved.