![](/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.