使用 C# 添加 entityFramework 部分

Add entityFramework section with C#

我们有一个 WPF 应用程序,可以使用内部开发的外部组件进行扩展。某些外部组件需要在组件安装期间将新部分(在本例中为 EntityFrameworkSection)添加到 WPF 应用程序的 app.config 中。但是,EntityFrameworkSection 似乎无法访问,因为它是内部 class.

我们的问题是,我们是否可以通过编程方式将 EntityFrameworkSection 添加到 app.config 中?

因为我碰巧使用 EF6,所以我最终使用了自 EF6 以来可用的 code base configuration。就我而言,我正在尝试添加与 MySQL 相关的配置。基本上我们需要做的是从 DbConfiguration 派生并将其设置为 EF 的配置。以下是我想出的:

源自DbConfiguration...

public class CustomDbConfiguration : DbConfiguration
{
    public CustomDbConfiguration()
    {
        SetProviderServices(MySqlProviderInvariantName.ProviderName, new MySqlProviderServices());
        SetProviderFactory(MySqlProviderInvariantName.ProviderName, new MySqlClientFactory());
    }
}

并像这样使用它:

class Program
{
    // 'DbConfiguration' should be treated as readonly. ONE AND ONLY ONE instance of 
    // 'DbConfiguration' is allowed in each AppDomain.
    private static readonly CustomDbConfiguration DBConfig = new CustomDbConfiguration();

    static void Main(string[] args)
    {
        // Explicitly set the configuration before using any features from EntityFramework.
        DbConfiguration.SetConfiguration(DBConfig);

        using (var dbContext = new MySQLDb())
        {
            var dbSet = dbContext.Set<Actor>();

            // Read data from database.
            var actors = dbSet.ToList();
        }

        using (var dbContext = new SQLDb())
        {
            var dbSet = dbContext.Set<User>();

            // Read data from database.
            var users = dbSet.ToList();
        }
    }
}

我的app.config只包含连接字符串的信息,如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
  <connectionStrings>
    <add name="MySQLDb" connectionString="server=localhost;port=3306;database=sakila;uid=some_id;password=some_password" providerName="MySql.Data.MySqlClient"/>
    <add name="SQLDb" connectionString="data source=.\SQLEXPRESS;initial catalog=some_db;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>