简体   繁体   中英

Add entityFramework section with C#

We have a WPF application which is extensible with external components developed in-house. Some external components requires new section (in this case, EntityFrameworkSection ) to be added into the app.config of the WPF application during the installation of the component. However, EntityFrameworkSection doesn't seems to accessible as it is an internal class.

Our question is, is it possible for us to programmatically add EntityFrameworkSection into app.config ?

Since I'm happen to use EF6, I ended up using code base configuration which is available since EF6. In my case, I'm trying to add configuration related to MySQL. Basically what we need to do is to derive from DbConfiguration and set it as the configuration for EF. Following is what I comes up with:

Deriving from DbConfiguration ...

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

and use it like this:

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();
        }
    }
}

My app.config only contains info for connection string, as follow:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM