与 Entity Framework 6 的动态 MySQL 连接
使用 Entity Framework 6 连接到动态数据库名称涉及某些注意事项。
获取 MySQL兼容性
<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>
动态数据库连接
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");
注意:如果使用数据库迁移,添加一个工厂类来传递种子方法中的数据库名称:
public class MigrationsContextFactory : IDbContextFactory<ApplicationDbContext> { public ApplicationDbContext Create() { return new ApplicationDbContext("developmentdb"); } }
以上是如何与 Entity Framework 6 建立动态 MySQL 连接?的详细内容。更多信息请关注PHP中文网其他相关文章!