问题描述
使用Entity Framework的迁移命令时是否可以配置/引导依赖项注入?
Is there way that dependency injection can be configured/bootstrapped when using Entity Framework's migration commands?
Entity Framework Core支持 DbContext依赖项注入
子类。该机制包括允许在 DbContext
之外配置数据访问。
Entity Framework Core supports dependency injection for DbContext
subclasses. This mechanism includes allowing for configuration of data access outside of of the DbContext
.
例如,以下将配置EF使用从 config.json
For example, the following would configure EF to persist to a SQL server using a connection string retrieved from config.json
ServiceCollection services = ...
var configuration = new Configuration().AddJsonFile( "config.json" );
services.AddEntityFramework( configuration )
.AddSqlServer()
.AddDbContext<BillingDbContext>( config => config.UseSqlServer() );
但是,迁移命令不知道要执行此代码,因此 Add-迁移
将因缺少提供程序或缺少连接字符串而失败。
However, the migrations commands do not know to execute this code so Add-Migration
will fail for lack of a provider or lack of a connection string.
可以通过覆盖 DbContext 子类中> OnConfiguring 来指定提供程序和配置字符串,但是当需要在其他地方进行不同的配置时,会遇到麻烦。最终,使迁移命令和代码都正常工作变得非常复杂。
Migrations can be made to work by overriding OnConfiguring
within the DbContext
subclass to specify the provider and configuration string, but that gets in the way when different configuration is desired elsewhere. Ultimately keeping my the migration commands and my code both working becomes undesirably complex.
注意:我的 DbContext
住在与使用它的入口点不同的程序集,我的解决方案有多个启动项目。
Note: My DbContext
lives in a different assembly than the entry point that uses it and my solution has multiple start-up projects.
推荐答案
为评论了Entity Framework 7中尚不存在此功能。GitHub问题
As @bricelam commented this functionality does not yet exist in Entity Framework 7. This missing functionality is tracked by GitHub issue aspnet/EntityFramework#639
同时,我发现的解决方法是利用全局状态而不是子类化的麻烦。通常不是我的第一个设计选择,但是它现在很有效。
In the mean time, the easier workaround I found was to utilize a global state rather than hassle with subclassing. Not usually my first design choice but it works well for now.
在MyDbContext中:
In MyDbContext:
public static bool isMigration = true;
protected override void OnConfiguring( DbContextOptionsBuilder optionsBuilder )
{
// TODO: This is messy, but needed for migrations.
// See https://github.com/aspnet/EntityFramework/issues/639
if ( isMigration )
{
optionsBuilder.UseSqlServer( "<Your Connection String Here>" );
}
}
在 Startup.ConfigureServices( )
。
public IServiceProvider ConfigureServices( IServiceCollection services )
{
MyContext.isMigration = false;
var configuration = new Configuration().AddJsonFile( "config.json" );
services.AddEntityFramework( configuration )
.AddSqlServer()
.AddDbContext<MyDbContext>( config => config.UseSqlServer() );
// ...
}
(配置代码实际上位于就我而言就是一个Autofac模块。)
(The configuration code actually lives in an Autofac Module in my case.)
这篇关于在Entity Framework Core中创建迁移时,如何配置DbContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!