4

Is it possible to create a code-first Entity Framework model that connects to an existing database using ODP.Net without having any settings in the app.config file?

I have tried many different things.

Currently I am setting DbConfiguration:

    sealed class EntityFrameworkConfiguration : DbConfiguration
    {
        public static readonly DbConfiguration Instance = new EntityFrameworkConfiguration();

        EntityFrameworkConfiguration()
        {
            this.SetDefaultConnectionFactory(new OracleConnectionFactory());
            this.SetProviderServices("Oracle.ManagedDataAccess.Client", EFOracleProviderServices.Instance);
        }
    }

    DbConfiguration.SetConfiguration(EntityFrameworkConfiguration.Instance);

I am passing an OracleConnection directly into the EF context.

However, I either have problems with the SQL being generated in SQL Server format (using double-quotes around table aliases), or I get the following error:

An unhandled exception of type 'System.NotSupportedException' occurred in EntityFramework.dll

Additional information: Unable to determine the provider name for provider factory of type 'Oracle.ManagedDataAccess.Client.OracleClientFactory'. Make sure that the ADO.NET provider is installed or registered in the application config.

Has anyone any experience of getting this to work without polluting app.config with crud?

Stephen Drew
  • 1,415
  • 19
  • 31

2 Answers2

5

Yes. To complete the switch from machine.config/app.config to code-based configuration, I had to also include a call to SetProviderFactory().

public sealed class EntityFrameworkConfiguration : DbConfiguration
{
    public static readonly DbConfiguration Instance = new EntityFrameworkConfiguration();

    public EntityFrameworkConfiguration()
    {
        SetDefaultConnectionFactory(new OracleConnectionFactory());
        SetProviderServices("Oracle.ManagedDataAccess.Client", EFOracleProviderServices.Instance);
        SetProviderFactory("Oracle.ManagedDataAccess.Client", new OracleClientFactory());
    }
}

I also called DbConfiguration.SetConfiguration(EntityFrameworkConfiguration.Instance); in the startup of my application because I had DbContext's in multiple assemblies that all needed to share this configuration.

On a side note, I have also found this to be effective in allowing your application to work around the ConfigurationErrorsException: The 'DbProviderFactories' section can only appear once per config file for cases where you may not have access to repair the user's machine.config.

Benjamin Brandt
  • 367
  • 3
  • 13
1

Uff. Found the problem.

Because I was registering column mapping using lower case the query didn't work. The column and table names must be in upper-case.

How silly.

Stephen Drew
  • 1,415
  • 19
  • 31