数据库启动时迁移



我读了很多关于启动时数据库迁移的文章,无论我使用什么方法,我的努力都不会有任何结果。我得到的主要问题是 no parameterless constructor defined for type startup

我有我的数据上下文

public class DataContext : DbContext
{
    public DataContext(DbContextOptions options) : base(options)
    {
    }
    public DataContext()
    {
    }
    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        if (options.IsConfigured)
        {
            //means that context has been added during dependency injection and no further action required.
            
        }
        else
        {
            //means context is being accessed during Add-Migration therefore we need to set the options. The whole DI/Configuration process won't have run yet, so need some other way to get connection string.
            //probably below is a bit too fancy, just hardcoding would be fine.  But anyway it seems to work and transfers to different developers machines
            //you must have {Values: { SqlConnectionString : xyz}} in local.settings.json in Unite.FunctionApp project dir
            var localSettingsJson =
                Path.Combine(local.settings.json");
            var config = new ConfigurationBuilder()
                .AddJsonFile(localSettingsJson, false)
                .Build();
            options.UseSqlServer(config["Values:SqlConnectionString"]);
        }
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {... }
我的<<p> strong>启动类
// register assembly
[assembly: FunctionsStartup(typeof(Startup))]
{
// inherit FunctionsStartup
public class Startup : FunctionsStartup
{
    private DataContext _context;
    public Startup(DataContext context)
    {
        _context = context;
    }
    public override void Configure(IFunctionsHostBuilder builder)
    {
        var executionContextOptions = builder.Services.BuildServiceProvider()
            .GetService<IOptions<ExecutionContextOptions>>().Value;
        var config = new ConfigurationBuilder()
            .SetBasePath(executionContextOptions.AppDirectory)
            .AddJsonFile("local.settings.json", true)
            .AddUserSecrets(Assembly.GetExecutingAssembly(), false)
            .AddEnvironmentVariables()
            .Build();
        builder.Services.AddSingleton<IConfiguration>(config);
        var sqlConnection = config["SqlConnectionString"] ??
                            throw new Exception("SQL Connection String Not Defined");
        builder.Services.AddDbContext<DataContext>(options => options.UseSqlServer(sqlConnection));
        _context.Database.MigrateAsync();
    }
}

}

如果我有我的无参数DataContext方法在我的类为什么我仍然得到这个问题,它没有定义?

在DataContext类的构造函数之前添加无参数构造函数。

最新更新