Wednesday, 15 February 2012

c# - How do you configure the DbContext when creating Migrations in Entity Framework 7? -


Dependency injection can be configured when using the migration command of the entity framework?

The unit framework 7 supports dependency injection for the subdivision of DbContext This mechanism includes permission to configure data access outside of DbContext . For example, to configure EF for a SQL server in the following, config.json

  servicon services = ... var configuration = new configuration () . AddJsonFile ("config.json"); Services.AddEntityFramework (Configuration) AddSqlServer () .AddDbContext & lt; Billing DBcinTex & gt; (Config = & gt; config.UseSqlServer ());  

However, the migration commands do not know to execute this code, so the ad-migration will fail due to lack of provider or lack of connection string .

Migration can be done to work by overriding OnConfiguring within the DbContext subclass to specify the provider and configuration string, but this It happens when different configurations go elsewhere and eventually my migration command and both of my code becomes extremely complicated.

Note: My DbContext remains in a separate assembly from the entry point which uses it and my solution is multiple start-up projects.

Note that this functionality does not yet exist in the unit framework 7. It is unavailable functionality,

In the mean time, I got the easy solution to use global position rather than trouble with sub-clinging, generally my first design is not like but it's good for now Works the way.

In MyDbContext:

  public static boolMigration = true; Protected override zero on-configuration (DBContext option builder option builder) {// TODO: This is dirty, but it is necessary for migration. // see https://github.com/aspnet/EntityFramework/issues/639 if (isMigration) {optionsBuilder.UseSqlServer ("& lt; your connection string here»;); }}  

in startup. Configure Services () .

  Public IserviceProvider Configure Services {MyContext.isMigration = false; Var configuration = new configuration (). AddJsonFile ("config.json"); Services.AddEntityFramework (Configuration) AddSqlServer () .AddDbContext & lt; MyDbContext & gt; (Config = & gt; config.UseSqlServer ()); // ...}  

(The configuration code actually stays in an autofac module in my case.)


No comments:

Post a Comment