How can you make EF migrations work without hardcoding a nameorconnectionstring in the base of the required parameterless constructor?
EF migrations is forcing you to add a default constructor to the custom dbcontext. In the base of the dbcontext you have to provide a nameorconnectionstring.
public class CustomDbContext : DbContextBase
{
public CustomDbContext ()
: base("theconnectionstringwedontwanttoset") //hardcoded connection string
{
}
The fact that we need to hardcode the constructor is something we cant work with since in our client applications we work without a config file and we dynamically build up the connection since we are connecting to many different databases (server, local sql compact).
After exploring the DbMigrationsConfiguration class I found a DbConnectionsInfo property named TargetDatabase which can be set in the constructor. But even this solution did not work. This is what I did:
public sealed class Configuration : DbMigrationsConfiguration<CustomDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
//Setting the TargetDatabase in the hope it will use it in the migration
TargetDatabase = new DbConnectionInfo("Server=xxx;Database=xxx;Trusted_Connection=True", "System.Data.SqlClient");
}
public class MigrationInitializer : MigrateDatabaseToLatestVersion<CustomDbContext, Configuration>
{
}
I can see that eventually the Activator.CreateInstance is used within DbMigrator and I expected from this class to use the TargetDatabase.Create...or something.
Any help or feedback is welcome.
Thanks in advance,
Wilko
it is possible yes See answers here I also included a test program in this question.