![](/img/trans.png)
[英]ASP.NET MVC Entity Framework code-first: no errors but tables aren't populated correctly
[英]ASP.NET Core with Entity Framework - code first migrations aren't reading my environment variables
我有一個首先使用實體框架代碼的ASP.NET Core 2 Web API。 我的DbContext
與API本身不在同一程序集中,因此允許我使用Microsoft.EntityFrameworkCore.Tools.DotNet
工具我已將IDesignTimeDbContextFactory<MyDbContext>
的實現添加到DbContext
的項目中:
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<MyDbContext>
{
private static IConfiguration _configuration;
public static IConfiguration Configuration
{
get
{
if (_configuration != null) return _configuration;
_configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{EnvName ?? "Production"}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
return _configuration;
}
}
public MyDbContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<MyDbContext>();
var connectionString = Configuration.GetConnectionString("MyConnString");
var migrationsAssembly = typeof(MyDbContext).GetTypeInfo().Assembly.GetName().Name;
builder.UseSqlServer(connectionString, b => b.MigrationsAssembly(migrationsAssembly));
return new MyDbContext(builder.Options);
}
}
我在這個項目中沒有appsettings.json
,但是我添加了一個名為ConnectionStrings:MyConnString
和連接字符串值的系統環境變量。
當我運行諸如dotnet ef migrations add "Whatever"
類的工具命令時, dotnet ef migrations add "Whatever"
那么我會收到一條錯誤消息,指出連接字符串不能為null。 因此,我猜配置生成器沒有讀取我的環境變量。 如果我將變量connectionString
替換為硬編碼的連接字符串,則可以正常工作。
誰能告訴我如何使它工作? 除了使用環境變量之外,還有其他方法可以使我的連接字符串保持秘密嗎? 據我所知,用戶機密只能用於Web項目。
顧名思義, IDesignTimeDbContextFactory
僅用於開發 。 它不支持環境,或實際上沒有任何環境概念。 這只是對類庫運行遷移的一種方法,由於它不是啟動項目,因此實際上DbContext
注入DbContext
。
總而言之,文檔出於某種原因對連接字符串進行了硬編碼。 沒有理由不對其進行硬編碼,因為它只能是所使用的一個連接字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.