[英]EF Core - Connection string cannot be null
我正在將ASP.Net Core 2.1
與EF Core 2.1
從PMC運行任何遷移時,出現以下錯誤
值不能為空。 參數名稱:connectionString
這是我的Context類的樣子
public class MyAppContextFactory : IDesignTimeDbContextFactory<MyAppContext>
{
private readonly string _dbConnection;
public MyAppContextFactory()
{
}
public MyAppContextFactory(string dbConnection)
: this()
{
_dbConnection = dbConnection;
}
public MyAppContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<MyAppContext>();
optionsBuilder.UseSqlServer(_dbConnection, opts => opts.CommandTimeout((int)TimeSpan.FromMinutes(15).TotalSeconds));
return new MyAppContext(optionsBuilder.Options);
}
}
我的連接字符串存在於appsettings.json的API層中,按照慣例,我不應該在API / UI層中添加對EF的任何引用。
在這種分層體系結構中,如何根據環境設置連接字符串?
謝謝。
我認為EF實際上是從2.0開始啟動您的應用程序以生成遷移。 您需要將DesignTimeDbContextFactory添加到您的項目中,該項目將查詢此用例的連接字符串,例如:
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<StorageContext>
{
public StorageContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false)
.AddJsonFile("appsettings.Development.json", optional: true)
.Build();
var builder = new DbContextOptionsBuilder<StorageContext>();
var connectionString = configuration.GetConnectionString("DefaultConnection");
builder.UseSqlServer(connectionString);
Console.WriteLine($"Running DesignTime DB context. ({connectionString})");
return new StorageContext(builder.Options);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.