使用带有 Azure Functions 的 EntityFrameworkCore 迁移的 DbContext 问题

Issue with DbContext using EntityFrameworkCore Migrations with Azure Functions

我有一个多项目解决方案,包括数据层和 Azure Functions 层。我在添加 entity framework 迁移时遇到问题。我收到一条错误消息,指出我的 DbContext 需要一个无参数构造函数。使用 WebApi 时我不需要这个,但自从切换到 Azure Function 后,我收到了这个错误。我怀疑这与 Functions 项目中的 Startup 配置有关,但我似乎无法找到一种方法来获取它。

在数据层我有一个 DbContext:

public class SampleContext : IdentityDbContext<User>, IDbContext
{

    public SampleContext(DbContextOptions options) : base(options)
    {

    }
}

我的函数应用有一个启动项class:

public class Startup : FunctionsStartup
{

    public override void Configure(IFunctionsHostBuilder builder)
    {
        var configurationConnectionString = Environment.GetEnvironmentVariable("ConnectionString");
        var localRoot = Environment.GetEnvironmentVariable("AzureWebJobsScriptRoot");
        var azureRoot = $"{Environment.GetEnvironmentVariable("Home")}/site/wwwroot";
        var actualRoot = localRoot ?? azureRoot;


        var config = new ConfigurationBuilder()
                .SetBasePath(actualRoot)
                .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables()
                .AddAzureAppConfiguration(options =>
                    {
                        options.Connect(configurationConnectionString)
                            .ConfigureKeyVault(kv =>
                            {
                                kv.SetCredential(new DefaultAzureCredential());
                            });
                    })
                .Build();

        ...

        IServiceCollection services = builder.Services;

        services.AddSingleton(config);

        string connectionString = config["DefaultConnection"];


        services.AddDbContext<SampleContext>(options =>
            SqlServerDbContextOptionsExtensions.UseSqlServer(options, connectionString)
         );

        ...

     }

}

我正在使用代码优先,当我尝试创建迁移时

   add-migration initial -c SampleContext -p sample.data -s sample.functions -v

我收到这个错误:

Using assembly 'Sample.Data'.
Using startup assembly 'Sample.Functions'.
Using application base 'F:\GitHub\Sample\Sample.Functions\bin\Debug\netcoreapp3.1'.
Using working directory 'F:\GitHub\Sample\Sample.Functions'.
Using root namespace 'Sample.Data'.
Using project directory 'F:\GitHub\Sample\Sample\Sample.Data\'.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider...
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 'SampleContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'SampleContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
 ---> System.MissingMethodException: No parameterless constructor defined for type 'Sample.Data.Infrastructure.SampleContext'.
   at System.RuntimeType.CreateInstanceDefaultCtorSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean fillCache)
   at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, Boolean wrapExceptions)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic, Boolean wrapExceptions)

谁能帮我解决这个问题?

这就是我的工作方式:

public void ConfigureServices(IFunctionsHostBuilder builder, IConfigurationRoot config)
{
    IServiceCollection services = builder.Services;

    services.AddSingleton(config);
    services.AddApplicationInsightsTelemetry();

    string connectionString = config.GetConnectionString("MyConnectionString");
    services.AddDbContext<MyDbContext>(
        options => SqlServerDbContextOptionsExtensions.UseSqlServer(options, connectionString)
        );

    services.RegisterServiceLayer();
}