How to add entity framework 6 provider in code?

c# connection-string entity-framework-6


I use Entity Framework 6 in a C# application and it works perfectly. When creating the Model, the app.config is generated with all the necessary configuration. Now I don't like having stuff in the app.config, so I use the connection string builder. I succeeded in removing everything out of the app.config file except of this:

    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />

If I remove this, it does not work. So how can I translate that config into c# code? How to I do that? I've looked at the code-based configuration ( however, it did not help.

My partial class that creates the connection string looks like that:

public partial class LogEntities
        public LogEntities(string serverName)
            : base(GetConnectionString(serverName))

        public static string GetConnectionString(string serverName)
            // Specify the provider name, server and database.
            const string databaseName = "_LOG";

            // Initialize the connection string builder for the underlying provider.
            SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder
                DataSource = serverName,
                InitialCatalog = databaseName,
                IntegratedSecurity = true,
                MultipleActiveResultSets = true

            // Initialize the EntityConnectionStringBuilder.
            System.Data.EntityClient.EntityConnectionStringBuilder entityBuilder = new System.Data.EntityClient.EntityConnectionStringBuilder();
            entityBuilder.Provider = "System.Data.SqlClient";

            // Set the provider-specific connection string.
            entityBuilder.ProviderConnectionString = sqlBuilder.ToString();

            // Set the Metadata location.
            entityBuilder.Metadata = @"res://*/myproject.LogModel.csdl|res://*/myproject.LogModel.ssdl|res://*/myproject.LogModel.msl";

            return entityBuilder.ConnectionString;

Thanks in advance for any help.

Popular Answer

In EF6 you can use Code Base configuration. Take a look at this article for more details. It shows how to set the default connection factory (use the SetDefaultConnectionFactory method). To set the provider you use the SetProviderServices method.

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why