Entity Framework Code First Configuration
Available from EF 6+ (Oct 2013).
Overriding DbConfiguration
//Configure EF for this application. Only one per app.
//Ideally in same assembly as DbContext
public class DataConfiguration : System.Data.Entity.DbConfiguration
{
public DataConfiguration()
{
//in ctor, call the config methods
//for Azure, retry common transient exceptions
SetExecutionStrategy("System.Data.SqlClient",
() => new System.Data.Entity.SqlServer.SqlAzureExecutionStrategy());
}
}
If it is in the same assembly as the DbContext, it is found automatically. Otherwise use the DbConfigurationTypeAttribute with typeof() or assembly-qualified name.
[DbConfigurationType(typeof(DataConfiguration))]
public class DataContext : DbContext
App.config configuration overrides any code configuration. See MSDN
<entityFramework codeConfigurationType="Data.DataConfiguration, Data">
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
Configurable: Retry strategy
SetExecutionStrategy - only built in strategy is SqlAzureExecutionStrategy.
- SqlAzureExecutionStrategy Ctor can take a maxRetryCount and a maxDelay
- Default is 5 retries up to 30 seconds.
- Override abstract DbExecutionStrategy to implement a non-Azure retry strategy.
- Throws a RetryLimitExceeded after it retries transient errors a few times.
Non-default transactions are also not supported (see MSDN)
Configurable: Change __MigrationHistory table
SetHistoryContext - use a customized history table
Create the HistoryContext like a normal DbContext:
//inherit from HistoryContext
public class CustomHistoryContext : HistoryContext
{
//use this ctor
public CustomHistoryContext(DbConnection dbConnection, string defaultSchema)
: base(dbConnection, defaultSchema)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//must call base
base.OnModelCreating(modelBuilder);
//change the defaults
modelBuilder.Entity<HistoryRow>().ToTable("DataVersioning", DefaultSchema);
}
}
Configurable: Default connection
SetDefaultConnectionFactory - When creating new database (i.e. no connection string)
SetDefaultConnectionFactory(
new System.Data.Entity.Infrastructure.LocalDbConnectionFactory("v11.0"));