Partilhar via


EF 4.3 Configuration File Settings

 


The information in this post is out of date.

Visit msdn.com/data/ef for the latest information on current and past releases of EF.

For Configuration File Settings see https://msdn.com/data/jj556606


 

We recently released Entity Framework 4.3 Beta 1 which includes the ability to configure more DbContext and Code First related settings from your applications Web.config or App.config file.

 

These Settings are Optional

Code First and the DbContext API follow a ‘convention over configuration’ principle. All the settings discussed in this post have a default behavior, you only need to worry about changing the setting when the default no longer satisfies your requirements.

All of these settings can also be applied using code. The configuration file option allows these settings to be easily changed during deployment without updating your code.

 

The Entity Framework Configuration Section

In earlier versions of Entity Framework you could set the database initializer for a context using the appSettings section of the configuration file. In EF 4.3 we are introducing the custom entityFramework section to handle the new settings. Entity Framework will still recognize database initializers set using the old format, but we recommend moving to the new format where possible.

The entityFramework section was automatically added to the configuration file of your project when you installed the EntityFramework NuGet package.

 <?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, 
visit https://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" 
      type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.0.0, 
Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>
</configuration>
  

Connection Strings

Setting a connection string for a context uses the same syntax as previous releases of Entity Framework.

Code First uses normal ADO.NET connection strings. For example:

 <connectionStrings>
  <add name="BlogContext" 
        providerName="System.Data.SqlClient" 
        connectionString="Server=.\SQLEXPRESS;Database=Blogging;Integrated Security=True;"/>
</connectionStrings>

This post provides more details on how Code First determines the database to be used, including connection strings in the configuration file.

 

The Database First and Model First approaches with an EDMX file use special EF connection strings. For example:

 <connectionStrings>
  <add name="BlogContext" 
        connectionString="metadata=res://*/BlogModel.csdl|
                                                              res://*/BlogModel.ssdl|
                                                              res://*/BlogModel.msl;
                                           provider=System.Data.SqlClient;
                                           provider connection string=
                                               &quot;data source=.\SQLEXPRESS;
                                               initial catalog=Blogging;
                                               integrated security=True;
                                               multipleactiveresultsets=True;&quot;" 
    providerName="System.Data.EntityClient" />
</connectionStrings>

 

Connection strings go in the standard connectionStrings element and do not require the new entityFramework section.

 

Code First Default Connection Factory

The new configuration section allows you to specify a default connection factory that Code First should use to locate a database to use for a context. The default connection factory is only used when no connection string has been added to the configuration file for a context.

To set a connection factory, you specify the assembly qualified type name in the deafultConnectionFactory element.
Note: An assembly qualified name is the namespace qualified name, followed by a comma, then the assembly that the type resides in. You can optionally also specify the assembly version, culture and public key token.

Here is an example of setting your own default connection factory:

<entityFramework>
<defaultConnectionFactory type="MyNamespace.MyCustomFactory, MyAssembly"/>
</entityFramework>

 

The above example requires the custom factory to have a parameterless constructor. If needed, you can specify constructor parameters using the parameters element.

For example, the SqlCeConnectionFactory, that is included in Entity Framework, requires you to supply a provider invariant name to the constructor. The provider invariant name identifies the version of SQL Compact you want to use. The following configuration will cause contexts to use SQL Compact version 4.0 by default.

 <entityFramework>
  <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
    <parameters>
      <parameter value="System.Data.SqlServerCe.4.0" />
    </parameters>
  </defaultConnectionFactory>
</entityFramework>

 

If you don’t set a default connection factory, Code First uses the SqlConnectionFactory, pointing to .\SQLEXPRESS. SqlConnectionFactory also has a constructor that allows you to override parts of the connection string. If you want to use a SQL Server instance other than .\SQLEXPRESS you can use this constructor to set the server.

The following configuration will cause Code First to use a LocalDB instance for contexts that don’t have an explicit connection string set.

 <entityFramework>
  <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
    <parameters>
      <parameter value="Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True" />
    </parameters>
  </defaultConnectionFactory>
</entityFramework>

 

By default, it’s assumed that constructor arguments are of type string. You can use the type attribute to change this.

 <parameter value="2" type="System.Int32" />

 

Database Initializers

Database initializers are configured on a per-context basis. They can be set in the configuration file using the context element. This element uses the assembly qualified name to identify the context being configured.

By default, Code First contexts are configured to use the CreateDatabaseIfNotExists initializer. There is a disableDatabaseInitialization attribute on the context element that can be used to disable database initialization.

For example, the following configuration disables database initialization for the Blogging.BlogContext context defined in MyAssembly.dll.

 <contexts>
  <context type=" Blogging.BlogContext, MyAssembly" disableDatabaseInitialization="true" />
</contexts>

 

You can use the databaseInitializer element to set a custom initializer.

 <contexts>
  <context type=" Blogging.BlogContext, MyAssembly">
    <databaseInitializer type="Blogging.MyCustomBlogInitializer, MyAssembly" />
  </context>
</contexts>

 

Constructor parameters use the same syntax as default connection factories.

 <contexts>
  <context type=" Blogging.BlogContext, MyAssembly">
    <databaseInitializer type="Blogging.MyCustomBlogInitializer, MyAssembly">
      <parameters>
        <parameter value="MyConstructorParameter" />
      </parameters>
    </databaseInitializer>
  </context>
</contexts>

 

You can configure one of the generic database initializers that are included in Entity Framework. The type name should specify your context as the TContext generic. The type attribute uses the .NET Framework format for generic types.

The following configuration sets the DropCreateDatabaseAlways<TContext> initializer for the BlogContext.
Note: The type name is wrapped in the example but must appear on a single line in your configuration file.

 <contexts>
  <context type=" Blogging.BlogContext, MyAssembly">
    <databaseInitializer type="System.Data.Entity.DropCreateDatabaseAlways`1[
[Blogging.BlogContext, MyAssembly]], EntityFramework" />
  </context>
</contexts>

 

If you are using Code First Migrations, you can configure the database to be migrated automatically using the MigrateDatabaseToLatestVersion<TContext, TMigrationsConfiguration> initializer.
Note: The type name is wrapped in the example but must appear on a single line in your configuration file.

 <contexts>
  <context type="Blogging.BlogContext, MyAssembly">
    <databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[Blogging.BlogContext, 
MyAssembly], [Blogging.Migrations.Configuration, MyAssembly]], EntityFramework" />
  </context>
</contexts>

 

Summary

In this walkthrough you saw how to use the configuration file to set connection strings, default connection factory and database initializers.

Rowan Miller
Program Manager
ADO.NET Entity Framework

Comments

  • Anonymous
    January 12, 2012
    I thought you guys were pushing convention over configuration, have you had a change of heart?

  • Anonymous
    January 12, 2012
    @Betty: no, we are not changing our minds. This is yet another way to express configurations that we are enabling in EF 4.3. It still fits in the convention over configuration paradigm: you won't need to use these configurations unless you want to override the decisions the conventions would make. Until now EF allowed overriding the conventions mostly in .NET code (e.g. by adding attributes to your types, invoking fluent APIs and passing a connection objects to the constructor of DbContext) and only a small amount of things could be configured in the configuration file of the application. We looked at various scenarios we wanted to enable and simplify (e.g. how to make LocalDB the default if SQL Express is not even installed in the machine?) and we realized that it was time to tidy up what we had in the configuration files.

  • Anonymous
    January 16, 2012
    @Betty – I’ve also added a section to the top of the post to make sure this is clearer.

  • Anonymous
    February 16, 2012
    The comment has been removed

  • Anonymous
    February 25, 2012
    NpgsqlFactory is a singleton object and hasn't a constructor, is there a way to make EF to use it anyway? currently i create a DbConnection manually and pass it in to DbContext..

  • Anonymous
    April 02, 2012
    context element ok its child of contexts but contexts?

  • Anonymous
    April 18, 2012
    IConfigurationConvention does not exist in EF 5 beta... has this been deprecated?  If not, what are we supposed to be using to set global attributes instead of manually setting each value/annotation?

  • Anonymous
    April 19, 2012
    @Joseph Baggett - Custom conventions aren't available in EF5, we did make them public for one of the EF4.1 Betas but it became clear we needed to do some work before including them in an RTM. We haven't done that work in EF5 but it is one of the top items on our backlog for the next release.

  • Anonymous
    June 16, 2012
    How do you remove default initializer (set to null) in .config file?

  • Anonymous
    June 18, 2012
    @Konstantin Tarkus Use disableDatabaseInitialization="true" as shown in the first example of the Database Initializers section.