实体框架6提供了一些方便的细微变化,有助于使MySQL工作,并创建动态数据库连接。
使用Entity Framework 6获取MySQL
首先,在我回答这个问题的日期,与EF6兼容的唯一的.Net连接器驱动程序是MySQL .Net Connectior 6.8.1(Beta开发版本),可以找到at the official MySQL website here。
安装后,从Visual Studio解决方案中引用以下文件:
> Mysql.Data.dll
> Mysql.Data.Entity.EF6.dll
您还需要将这些文件复制到构建期间可以访问项目的位置,例如bin目录。
接下来,您需要添加一些项目到您的Web.config(或App.config如果在基于桌面的)文件。
连接字符串:
connectionString="Server=localhost;Database=dbName;Uid=username;Pwd=password"
providerName="MySql.Data.MySqlClient" />
另外添加提供者,在< entityFramework />和< providers />节点,可选(在处理动态定义的数据库时,这是我答案的第二部分绝对必须的),您可以更改< defaultConnectionFactory />节点:
如果从默认的sql server连接更改defaultConnectionFactory,不要忘记删除< parameter>嵌套在defaultConnectionFactory节点中的节点。 MysqlConnectionFactory对其构造函数不采用任何参数,如果参数仍然存在,则它将失败。
在这个阶段,用Entity连接到MySQL很容易,你可以通过名字来引用上面的connectionString。请注意,如果通过名称连接,即使defaultConnectionFactory节点仍然指向SQL Server(默认情况下它),这将会起作用。
public class ApplicationDbContext: DbContext
{
public ApplicationDbContext() : base("mysqlCon")
{
}
}
这只是正常连接的问题:
ApplicationDbContext db = ApplicationDbContext();
连接到动态选择的数据库名称
在这一点上,很容易连接到一个可以作为参数传递的数据库,但是我们需要做一些事情。
重要的提示
If you have not already, you MUST change the defaultConnectionFactory in Web.config if you wish to connect to MySQL
dynamically. Since we will be passing a connection string directly to
the context constructor, it will not know which provider to use and
will turn to its default connection factory unless specified in
web.config. See above on how to do that.
您可以将连接字符串手动传递给上下文,如下所示:
public ApplicationDbContext() : base("Server:localhost;...")
{
}
但是为了让它更容易一些,我们可以在设置mySQL时对我们上面提供的连接字符串做一个小的改动。只需添加一个占位符,如下所示:
现在我们可以构建一个帮助方法并更改ApplicationDbContext类,如下所示:
public class ApplicationDbContext: DbContext
{
public ApplicationDbContext(string dbName) : base(GetConnectionString(dbName))
{
}
public static string GetConnectionString(string dbName)
{
// Server=localhost;Database={0};Uid=username;Pwd=password
var connString =
ConfigurationManager.ConnectionStrings["mysqlCon"].ConnectionString.ToString();
return String.Format(connString, dbName);
}
}
如果您正在使用数据库迁移,以下步骤很重要
如果您正在使用迁移,您将发现ApplicationDbContext将被框架传递给您的Seed方法,它将失败,因为它不会传入我们为数据库名称输入的参数。
将下面的类添加到上下文类的底部(或任何地方)来解决这个问题。
public class MigrationsContextFactory : IDbContextFactory
{
public ApplicationDbContext Create()
{
return new ApplicationDbContext("developmentdb");
}
}
您的代码优先迁移和种子方法现在将定位到MySQL数据库中的developmentdb模式。
希望这有助于某人:)