Entity Framework 6 的动态 MySQL 数据库连接 [英] Dynamic MySQL database connection for Entity Framework 6

查看:50
本文介绍了Entity Framework 6 的动态 MySQL 数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将动态连接字符串传递给实体框架上下文.我有超过 150 个相同的模式(每个帐户一个),我想选择这样的连接:

I wish to pass a dynamic connection string to the entity framework context. I have over 150 schemas which are identical (one per account) and I would like to select the connection as such:

ApplicationDbContext db = new ApplicationDbContext("dbName");

理论上这很容易,因为我可以创建一个 connectionString 并将其作为构造函数的参数传递,例如:

In theory this would be fairly easy, as I can create a connectionString and pass it as the argument for the constructor, for example:

public ApplicationDbContext(string dbName) : base(GetConnectionString(dbName))
{
}

public static string GetConnectionString(string dbName)
{
    // The connectionString passed is something like:
    // Server=localhost;Database={0};Uid=username;Pwd=password
    var connString =  ConfigurationManager
                         .ConnectionStrings["MyDatabase"]
                         .ConnectionString
                         .ToString();

    return String.Format(connString, dbName);
}

当我只传递连接字符串名称时,我可以成功连接,但当我动态生成它时,如下所示.我现在意识到这是因为 web.config 中的连接字符串中有 providerName="MySql.Data.MySqlClient" 属性.

I can connect successfully when I just pass the connection string name, but not when I generate it dynamically as below. I realize now that it's because the connection string in web.config has the providerName="MySql.Data.MySqlClient" attribute in it.

当我将实际的连接字符串动态传递给连接时,它假定它需要连接到 SQL Server 而不是 MySQL,并且由于连接字符串无效而失败.

When I pass the actual connection string dynamically to the connection though, it assumes that it needs to connect to SQL Server rather than MySQL and fails due to the connection string being invalid.

问题是,如果我是动态创建的,如何将提供者名称传递给连接字符串?

The question is, how do I pass the provider name to the connection string if I am creating it dynamically?

推荐答案

Entity Framework 6 提供了一些方便的细微变化,有助于让 MySQL 工作并创建动态数据库连接.

Entity Framework 6 offers some handy subtle changes which aid in both getting MySQL working and also creating dynamic database connections.

首先,在我回答这个问题的日期,唯一与 EF6 兼容的 .Net 连接器驱动程序是 MySQL .Net Connectior 6.8.1(Beta 开发版),可以找到 在 MySQL 官方网站这里.

First, at the date of my answering this question, the only .Net connector drivers compatible with EF6 is the MySQL .Net Connectior 6.8.1 (Beta development version) which can be found at the official MySQL website here.

安装后,从您的 Visual Studio 解决方案中引用以下文件:

After installing, reference the following files from your Visual Studio solution:

  • Mysql.Data.dll
  • Mysql.Data.Entity.EF6.dll

您还需要将这些文件复制到项目在构建期间可以访问的某个位置,例如 bin 目录.

You will also need to copy these files somewhere where they will be accessible to the project during build time, such as the bin directory.

接下来,您需要将一些项目添加到您的 Web.config(或 App.config,如果基于桌面)文件.

Next, you need to add some items to your Web.config (or App.config if on desktop based) file.

连接字符串:

<connectionStrings>
    <add name="mysqlCon"
         connectionString="Server=localhost;Database=dbName;Uid=username;Pwd=password" 
         providerName="MySql.Data.MySqlClient" />
</connectionStrings>

同时在 节点中添加提供者,可选(这是第二部分中绝对必须的)在我的回答中,在处理动态定义的数据库时)您可以更改 <defaultConnectionFactory/> 节点:

Also add the provider, inside the <entityFramework /> and <providers /> nodes, optionally (this is an absolute must in the second part of my answer, when dealing with dynamically defined databases) you may change the <defaultConnectionFactory /> node:

<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>

如果您从默认的 sql server 连接更改 defaultConnectionFactory,请不要忘记删除嵌套在 defaultConnectionFactory 节点中的 节点.MysqlConnectionFactory 的构造函数不接受任何参数,如果参数仍然存在就会失败.

If you change the defaultConnectionFactory from the default sql server connection, don't forget to remove the <parameter> nodes which are nested in the defaultConnectionFactory node. The MysqlConnectionFactory does not take any parameters for its constructor and will fail if the parameters are still there.

在这个阶段,用Entity连接MySQL是很容易的,你可以通过名字引用上面的connectionString.请注意,如果按名称连接,即使 defaultConnectionFactory 节点仍指向 SQL Server(默认情况下),这也将起作用.

At this stage, it's quite easy to connect to MySQL with Entity, you can just refer to the connectionString above by name. Note that if connecting by name, this will work even if the defaultConnectionFactory node still points at SQL Server (which it does by default).

public class ApplicationDbContext: DbContext
{
    public ApplicationDbContext() : base("mysqlCon")
    {
    }
}

这只是正常连接的问题:

The it is just a matter of connecting normally:

ApplicationDbContext db = ApplicationDbContext();

<小时>

连接到动态选择的数据库名称

此时很容易连接到我们可以作为参数传递的数据库,但我们需要做一些事情.


Connecting to a dynamically selected database name

At this point it's easy to connect to a database which we can pass as a parameter, but there's a few things we need to do.

如果你还没有,如果你想连接到 MySQL,你必须改变 Web.config 中的 defaultConnectionFactory动态.由于我们将直接将连接字符串传递给上下文构造函数,它不会知道使用哪个提供程序和除非指定,否则将转向其默认连接工厂网络配置.请参阅上文了解如何执行此操作.

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.

您可以像这样手动将连接字符串传递给上下文:

You could pass a connection string manually to the context like this:

public ApplicationDbContext() : base("Server:localhost;...")
{
}

但是为了让它更容易一些,我们可以对上面在设置 mySQL 时所做的连接字符串进行一些小的更改.只需添加一个占位符,如下所示:

But to make it a little bit easier, we can make a small change to the connection string we made above when setting up mySQL. Just add a placeholder as shown below:

<add name="mysqlCon" connectionString="Server=localhost;Database={0};Uid=username;Pwd=password" providerName="MySql.Data.MySqlClient" />

现在我们可以构建一个辅助方法并更改ApplicationDbContext类,如下所示:

Now we can build a helper method and change the ApplicationDbContext class as shown below:

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 方法,并且它会失败,因为它不会传入我们为数据库名称设置的参数.

If you are using database migrations, the following step is important

If you are using migrations, you will find that the ApplicationDbContext will be passed to your Seed method by the framework and it will fail because it will not be passing in the parameter we put in for the database name.

将以下类添加到上下文类的底部(或任何地方)以解决该问题.

Add the following class to the bottom of your context class (or anywhere really) to solve that problem.

public class MigrationsContextFactory : IDbContextFactory<ApplicationDbContext>
{
    public ApplicationDbContext Create()
    {
        return new ApplicationDbContext("developmentdb");
    }
}

您的代码优先迁移和种子方法现在将针对 MySQL 数据库中的 developmentdb 架构.

Your code-first migrations and seed methods will now target the developmentdb schema in your MySQL database.

希望这对某人有所帮助:)

Hope this helps someone :)

这篇关于Entity Framework 6 的动态 MySQL 数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆