You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET7执行Add-Migration InitMigration时无法创建GasContext对象的原因

解决.NET7中Add-Migration无法创建GasContext的问题

问题场景

在.NET7环境下,通过Visual Studio程序包管理器控制台执行Add-Migration InitMigration命令添加迁移时,出现错误提示:Unable to create an object of type 'GasContext'。已确认:

  • GasContext同时存在带参和无参构造函数
  • 启动项目设置正确
  • DbContext与模型位于不同的类库项目中,API项目为新建空项目,无Program.cs初始配置

错误堆栈信息

Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider in assembly 'Context_Project'...
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 'GasContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'GasContext'. 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' while attempting to activate 'Context_Project.GasContext'.
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass21_4.<FindContextTypes>b__13()
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass21_4.<FindContextTypes>b__13()
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType, String namespace)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to create an object of type 'GasContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

项目结构与GasContext代码

项目分为三个部分:

  • Context项目:类库,存放GasContext
  • Models项目:类库,存放实体模型
  • API项目:空Web项目,作为启动项目,无Program.cs初始配置

GasContext代码如下:

public class GasContext : DbContext
{
    public GasContext(DbContextOptions Options) : base(Options)
    {
    
    }
    public GasContext()
    {
    
    }
    /*
        My DbSets
    */

    protected override void OnConfiguring(DbContextOptionsBuilder dbContextOptionsBuilder)
    {
            dbContextOptionsBuilder.UseSqlite("Data Source=GasPr.db");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        /*
            Some stuff.
        */
    }
}

解决方案

方案1:实现IDesignTimeDbContextFactory接口

在Context项目中添加一个设计时工厂类,让EF Core通过该工厂创建GasContext实例:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;

namespace Context_Project
{
    public class GasContextDesignTimeFactory : IDesignTimeDbContextFactory<GasContext>
    {
        public GasContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<GasContext>();
            optionsBuilder.UseSqlite("Data Source=GasPr.db");

            return new GasContext(optionsBuilder.Options);
        }
    }
}

添加后重新执行Add-Migration InitMigration命令即可。

方案2:在API项目中配置DbContext服务

在API项目的Program.cs中添加DbContext的依赖注入配置(如果API项目原本为空,需先添加Program.cs):

var builder = WebApplication.CreateBuilder(args);

// 注册GasContext
builder.Services.AddDbContext<GasContext>(options =>
    options.UseSqlite("Data Source=GasPr.db"));

var app = builder.Build();

app.Run();

然后在程序包管理器控制台执行命令时指定启动项目和上下文:

Add-Migration InitMigration -Context GasContext -StartupProject [你的API项目名称]

方案3:修改带参构造为泛型版本

将GasContext的带参构造函数修改为泛型的DbContextOptions<GasContext>,确保EF Core能正确识别:

public GasContext(DbContextOptions<GasContext> options) : base(options)
{
}

同时确保无参构造函数能通过OnConfiguring正确配置数据库连接,再重新执行迁移命令。


内容的提问来源于stack exchange,提问作者Burryaga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 03:35:08