问题描述
我已经阅读了很多关于启动时数据库迁移的文章,无论我使用什么方法,我的努力都无济于事。我遇到的主要问题是 no parameterless constructor defined for type startup
我有我的 DataContext 类
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)
{... }
我的创业班
// 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 方法,为什么我仍然遇到这个未定义的问题?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)