使用C#添加entityFramework部分

时间:2019-05-09 05:37:50

标签: c# mysql entity-framework-6 app-config

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

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

1 个答案:

答案 0 :(得分:0)

由于我刚好使用EF6,所以我最终使用了code base configuration,该版本自EF6起可用。就我而言,我正在尝试添加与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>