code-based Configuration:
The Entity Framework 6 has introduced code based configuration. Now, you can configure Entity Framework related settings using the code which had been previously configured in the <en Tityframework> section of the app. However, App. Config takes precedence over code-based configuration. In other words, if a configuration option is set in both the code and in the config file, then the setting in the config F Ile is used.
Let's see how to implement code-based configuration using Entity Framework 6.
First of all, you need to create a new class that derives the Dbconfiguration (System.Data.Entity.DbConfiguration ) Class:
Public class fe6codeconfig:dbconfiguration{ public fe6codeconfig () { // Define configurationhere }}
Now, you can set codeconfigurationtype in the config file as shown below:
<codeconfigurationtype= "Ef6dbfirsttutorials.fe6codeconfig, Ef6dbfirsttutorials "></entityframework>
Or You can use the Dbconfigurationtype attribute in the context class to set the Code-based configuration class:
Note: EF does not support has multiple configuration classes used in the same AppDomain. If You use this attribute, the to set different the configuration classes for the contexts, then the exception would be thrown.
Now, you can use different methods of dbconfiguration using the the constructor as shown below:
Let's see how does different settings using code-based configuration as well as the config file.
Set Default Connection Factory:
code-based configuration:
Public class fe6codeconfig:dbconfiguration { public fe6codeconfig () { this. Setdefaultconnectionfactory (new System.Data.Entity.Infrastructure.SqlConnectionFactory ());} }
Config file:
< EntityFramework > < type= "System.Data.Entity.Infrastructure.SqlConnectionFactory, entityframework"/ ></entityframework>
Set Database Provider:
code-based configuration:
Public class fe6codeconfig:dbconfiguration{ public fe6codeconfig () { this. Setproviderservices ("System.Data.SqlClient", System.Data.Entity.SqlServer.SqlProviderServices.Instance);} }
Config file:
< EntityFramework > < providers > < invariantname= "System.Data.SqlClient" type= " System.Data.Entity.SqlServer.SqlProviderServices, entityframework.sqlserver "/> </providers></entityframework>
Set Database Initializers:
You can set database initializers (for Code-first only) using code-based configuration as shown below:
Public class fe6codeconfig:dbconfiguration{ public fe6codeconfig () { this. Setdatabaseinitializer<schooldbentities> (new customdbinitializer<schooldbentities>()) ; }}
Config file:
<EntityFramework> <Contexts> <Contexttype= "ef6dbfirsttutorials.schooldbentities, ef6dbfirsttutorials" > <Databaseinitializertype= "Ef6dbfirsttutorials.customdbinitializer, ef6dbfirsttutorials"> </Databaseinitializer> </Context> </Contexts> </EntityFramework>
Download Sample Project for code-based configuration demo.
Entity Framework 6.0 Tutorials (3): code-based Configuration