将参数传递给 EF Core 的 IDesignTimeDbContextFactory [英] Pass arguments to IDesignTimeDbContextFactory of EF Core
问题描述
我们如何将参数传递给 dotnet ef 数据库更新?
How can we pass arguments to dotnet ef database update?
我希望能够使用参数更新不同的数据库.
i want to be able to update different database with the use of arguments.
我试过了
dotnet ef 数据库更新接受"
dotnet ef database update "Accept"
dotnet ef 数据库更新接受
dotnet ef databse update Accept
但是没有用..
或者我如何放置一个开关以从我的配置中获取不同的 conenctionString?
Or how I can put a switch to get different conenctionString from my configuration?
public ProjectContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
// Find a way to get different connection string
var connectionString = configuration.GetConnectionString(args[0]);
var builder = new DbContextOptionsBuilder<ProjectContext >();
builder.UseSqlServer(connectionString);
return new ProjectContext(builder.Options);
}
推荐答案
.NET 5 将在本回答发布后的几周内发布.所以这是有可能改变的.
.NET 5 releases in a couple weeks from the time of this answer. So this is possible to change.
立即回答
.NET 5 和相关的 EF Core 5+ NuGet 支持这一点.在包管理器中,您可以输入:
The .NET 5, and the associated EF Core 5+ NuGets support this. In Package Manager you can type:
Add-Migration YourMigrationName -Args "Space Separated Args"
Update-Database -Args "Space Separated Args"
例如,我使用这个:
Update-Database -Args MyConnName
在我的 Startup 项目中,我有一个包含该连接字符串键的配置文件(或 appsettings.json),然后我将其拉入.
In my Startup project I have a config file (Or appsettings.json) that has that connection string key, and I pull that in.
注意我说的是 .NET Core 5.这将在几周后发布完整版本.所以几周后,这个答案可能很简单.但在那之前,您可能需要安装预览版(和 NuGet PreReleases)
Note I said .NET Core 5. This will be have a full release in a few weeks from now. So in a few weeks this answer may be simple. But until then, you may need to install Preview versions (And NuGet PreReleases)
在此之前回答
问这个问题时缺少选项,尽管有选项,比如使用 dotnet ef commands
和 AppArgs
,作为 在此讨论.但是这些已经改变,现在也可以从 PM 控制台访问,如上面现在"中所讨论的.回答.
There were lacking options when this question was asked, though there were options, like using dotnet ef commands
with AppArgs
, as discussed here. But these have changed, and are also now accessible from PM Console as discussed in the above "Now" answer.
这篇关于将参数传递给 EF Core 的 IDesignTimeDbContextFactory的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!