How to use EF CodeFirst Migrations without hardcoding nameOrConnectionString

How can you perform EF migration without hard coding the nameconnectionString name in the database of the required constructor without parameters?

EF transitions force you to add a default constructor to your custom dbcontext. In the dbcontext database, you must specify the nameorconnection string.

public class CustomDbContext : DbContextBase { public CustomDbContext () : base("theconnectionstringwedontwanttoset") //hardcoded connection string { } 

The fact that we need to hard code the constructor is something we cannot work with, because in our client applications we work without a configuration file, and we dynamically increase the connection, because we connect to many different databases (server, local sql compact).

After studying the DbMigrationsConfiguration class, I found a DbConnectionsInfo property called 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 see that Activator.CreateInstance is ultimately used in DbMigrator, and I expected from this class to use TargetDatabase.Create ... or something like that.

Any help or feedback is appreciated.

Thanks in advance,

Wilko

+4
source share
1 answer

maybe yes . See the answers here. I also included a test program in this question.

0
source

Source: https://habr.com/ru/post/1447227/


All Articles