Entity framework 如何从命令行指定到dbcontext的连接字符串
我有一个包含两个项目的解决方案。一个asp.net核心和类lib dotnet.core。我使用类库只是为了运行迁移。我希望在调用“dotnet ef数据库更新”时能够将连接字符串从dev切换到prod。有没有干净的方法可以做到这一点?当您想根据环境类型更改连接字符串时,可以使用Entity framework 如何从命令行指定到dbcontext的连接字符串,entity-framework,asp.net-core,Entity Framework,Asp.net Core,我有一个包含两个项目的解决方案。一个asp.net核心和类lib dotnet.core。我使用类库只是为了运行迁移。我希望在调用“dotnet ef数据库更新”时能够将连接字符串从dev切换到prod。有没有干净的方法可以做到这一点?当您想根据环境类型更改连接字符串时,可以使用--Environment: -e |--environment要使用的环境。如果省略,则使用“开发”。 指定是Dev还是Prod,然后基于此重写连接字符串。如果您在package manager控制台中使用dotne
--Environment
:
-e |--environment要使用的环境。如果省略,则使用“开发”。
指定是Dev还是Prod,然后基于此重写连接字符串。如果您在package manager控制台中使用dotnet cli或--context命令,则可以通过传递“-c”参数来告诉entity framework要更新的db上下文
dotnet ef数据库更新-c{DbContextName}
或
更新数据库--上下文{DbContextName}
如果要在运行时根据环境更改连接字符串,可以使用
dotnet运行-e |--environment{EnvironmentName}
然后在Starup.cs方法中的configure services方法中执行以下操作
public IHostingEnvironment hostingEnv;
public void ConfigureServices(IServiceCollection services)
{
if (hostingEnv.IsEnvironment("{EnvironmentName}"))
{
services.AddDbContext<DbContextName>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DbContextNameFromAppSettings.JsonFile")));
}
else
{
services.AddDbContext<DbContextName>(options =>
options.UseSqlServer(Configuration.GetConnectionString("OtherDbContextNameFromAppSettings.JsonFile")));
}
}
public IHostingEnvironment hostingEnv;
public void配置服务(IServiceCollection服务)
{
if(hostingEnv.IsEnvironment(“{EnvironmentName}”))
{
services.AddDbContext(选项=>
使用SQLServer(Configuration.GetConnectionString(“DbContextNameFromAppSettings.JsonFile”);
}
其他的
{
services.AddDbContext(选项=>
使用SQLServer(Configuration.GetConnectionString(“OtherDbContextNameFromAppSettings.JsonFile”);
}
}
public IHostingEnvironment hostingEnv;
public void ConfigureServices(IServiceCollection services)
{
if (hostingEnv.IsEnvironment("{EnvironmentName}"))
{
services.AddDbContext<DbContextName>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DbContextNameFromAppSettings.JsonFile")));
}
else
{
services.AddDbContext<DbContextName>(options =>
options.UseSqlServer(Configuration.GetConnectionString("OtherDbContextNameFromAppSettings.JsonFile")));
}
}