i use EF5 code-first and set my initializers in the config. I want to use more than one database of the same context-type in one application. My connection strings look as follows:
<add name="DatabaseProduction" connectionString="Server=localhost; Database=DatabaseProduction; User Id=***; password=***" providerName="System.Data.SqlClient"/>
<add name="DatabaseTest" connectionString="Server=localhost; Database=DatabaseTest; User Id=***; password=***" providerName="System.Data.SqlClient"/>
I can use my contexts in the code like this
var _contextProd = new MyContext("DatabaseProduction");
var _contextTest = new MyContext("DatabaseTest");
The normal way to set the database initializer is the config file as explained here. But as far as i understand i can set the initializer on a per-context basis but not one for each connection string. Wrong?
The question is: How to set e.g. a DropCreateAllwaysInitializer for the Test Database while having a CreateDatabaseIfNotExistsInitializer on the Production Database?
============ Edit in answer to Gert’s comment and for clearification ============
The way i usually define my Initializers is
<contexts>
<context type=" Namespace.MyContext, MyAssembly">
<databaseInitializer type="Namespace.MyCustomContextInitializer, MyAssembly" />
</context>
</contexts>
And I could for sure add a second <context...> here and define the initializer for another context. But how to tell which initializer is used at which connection string? My problem in other words:
- The connection string has no knowledge about which context is there.
- the context (in the context section) has no knowledge at which connection string it is linked
- In code behind i tell the context which connection string to use
- the initializer for a particular context seems to be kind of static for each context type.
Again, how do i define a particular initializer for a pair of context and connection string?
The only way I can think of is to derive a context for each of your connection strings:
and
You can then set your initializers for each of the derived contexts.