Dynamic MySQL Connection with Entity Framework 6
Connecting to a dynamic database name using Entity Framework 6 involves certain considerations.
Getting MySQL Compatibility
<connectionStrings> <add name="mysqlCon" connectionString="Server=localhost;Database={0};Uid=username;Pwd=password" providerName="MySql.Data.MySqlClient" /> </connectionStrings> <entityFramework> <defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF6" /> <providers> <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" /> </providers> </entityFramework>
Dynamic Database Connection
public static string GetConnectionString(string dbName) { var connString = ConfigurationManager.ConnectionStrings["mysqlCon"].ConnectionString.ToString(); return String.Format(connString, dbName); }
public class ApplicationDbContext : DbContext { public ApplicationDbContext(string dbName) : base(GetConnectionString(dbName)) { } }
ApplicationDbContext db = new ApplicationDbContext("dbName");
Note: If using database migrations, add a factory class to pass the database name in the seed method:
public class MigrationsContextFactory : IDbContextFactory<ApplicationDbContext> { public ApplicationDbContext Create() { return new ApplicationDbContext("developmentdb"); } }
The above is the detailed content of How to Establish a Dynamic MySQL Connection with Entity Framework 6?. For more information, please follow other related articles on the PHP Chinese website!