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

EFCore指定不同启动项目执行迁移时无法创建SampleApiDbContext问题求助

报错根因

  • EF Core设计时工具无法识别Azure Functions专用的FunctionsStartup注入逻辑,无法获取你配置的SampleApiDbContext初始化参数
  • 你当前的SampleApiDbContext包含无参构造函数,工具调用无参构造创建实例时未配置数据库连接,直接导致初始化失败

解决步骤

方案1(推荐):添加EF Core设计时工厂

在存放SampleApiDbContext的Core项目中新增SampleApiDbContextFactory类,代码如下:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System.IO;

public class SampleApiDbContextFactory : IDesignTimeDbContextFactory<SampleApiDbContext>
{
    public SampleApiDbContext CreateDbContext(string[] args)
    {
        IConfiguration configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddEnvironmentVariables()
            .Build();

        var optionsBuilder = new DbContextOptionsBuilder<SampleApiDbContext>();
        optionsBuilder.UseSqlServer(
            configuration.GetValue<string>("SqlConnectionString"),
            b => b.MigrationsAssembly("Dymak.SampleLibraryApi.Admin")
        );

        return new SampleApiDbContext(optionsBuilder.Options);
    }
}

配置完成后直接执行原迁移命令即可,该方案一劳永逸,后续所有迁移、数据库更新操作都不需要额外加参数。

方案2:临时指定连接字符串

  1. 删掉SampleApiDbContext中的无参构造方法
  2. 执行迁移命令时增加--connection参数直接传入连接字符串:
dotnet ef --startup-project ..\Dymak.SampleLibraryApi migrations add Initial --connection "你的SqlServer实际连接字符串"

额外注意事项

如果选择方案1,执行迁移命令前需要确保当前终端的环境变量中存在SqlConnectionString,Windows环境下可以在终端提前执行配置:

  • Cmd:set SqlConnectionString=你的连接字符串
  • PowerShell:$env:SqlConnectionString="你的连接字符串"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 10:54:03