可以使用配置文件或代碼(EF6起)配置EF框架。
一、使用配置文件
安裝Entity Framework自動生成的配置
當使用VS的NuGet自動安裝Entity Framework(本文使用6.2.0)時會自動生成一些代碼。在xxx.config中會自動添加一些配置
一個空的配置文件:
<?xml version="1.0" encoding="utf-8"?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" /> </startup> </configuration>
安裝Entity Framework后配置文件變為:
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" /> </startup> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> <parameters> <parameter value="mssqllocaldb" /> </parameters> </defaultConnectionFactory> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework> </configuration>
可以看到增加了<configSections>、<entityFramework>配置節,這些配置都是針對微軟SqlServer數據庫的,如果使用其他數據庫還有修改一下。
如果將<configSections>配置節刪掉,運行程序會拋異常,異常拋出的位置為DbContext初始化的時候。
所以<configSections>配置節是必須的,其作用是創建自定義配置節,配置EF框架。默認生成的自定義配置節名稱為entityFramework,所以下面的<entityFramework>也是必須的。
自動生成的<entityFramework>配置節中包含了<defaultConnectionFactory>、<providers>這兩個配置節。其實只包含<providers>配置節就可以了且是必須的。
<defaultConnectionFactory>配置節的作用是配置code first默認連接工廠。此配置節下的<parameters>用來指定連接工廠構造函數的參數,如果參數是多個可以配置多個。
<providers> 配置節的作用是指定訪問數據庫的客戶端dll(EF6起)。
自此默認的配置解析完了,接下來是非自動生成的配置。
需手動配置的部分
<connectionStrings>配置節用於配置數據庫連接字符串,是必須配置的(一定程度上,若不配置則要顯示傳遞數據庫連接給上下文)。
<entityFramework>下的<contexts> 配置節是選配的,作用是配置自定義數據庫上下文,完成數據庫初始化。
<entityFramework>下的<interceptors>配置節配置攔截器(EF6.1起)。
例:
<interceptors>
<interceptor type="XXXX, XX">
<parameters>
<parameter value="param"/>
</parameters>
</interceptor>
</interceptors>
<interceptor>的type逗號前是類名(含命名空間),逗號后是命名空間,<parameters> 配置節配置類構造函數的參數。
<entityFramework>的屬性codeConfigurationType配置數據庫連接配置,必選。如果連接配置是自定義的擴展自DbConfiguration的類,那么要配置這個自定義類。
二、使用代碼完成配置
使用代碼完成配置要做到以下幾項
1)創建System.Data.Entity.DbConfiguration類的子類
2)在子類構造函數中調用DbConfiguration的方法進行配置。
3) 將繼承自DbConfiguration的子類傳給DbConfigurationType特性,啟用配置
DbConfiguration中的方法
protected internal void SetDefaultConnectionFactory(IDbConnectionFactory connectionFactory);
設置數據庫連接工廠,對應<defaultConnectionFactory>配置節
protected internal void AddInterceptor(IDbInterceptor interceptor);
設置數據庫攔截器,對應<interceptor>配置節
protected internal void SetExecutionStrategy(string providerInvariantName, Func<IDbExecutionStrategy> getExecutionStrategy);
設置訪問數據庫的客戶端dll,對應<provider>配置節
三、示例(EF6.0.0)
以MySql為例說明只使用配置文件、只使用編碼方式、使用配置文件和編碼結合的方式完成配置。
EF操作MySql涉及到兩個dll:MySql.Data.Entity,MySql.Data.Entity.EF6.dll(適用於.NET Framework 4.0 或.NET Framework 4.5),一般使用MySql.Data.Entity.EF6.dll
使用配置文件
<configuration> <configSections> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/> </startup> <connectionStrings> <clear/> <!--清除默認的連接字符串,務必加上!!!--> <add name="Master" connectionString="database=ef_otestdb;server=192.168.107.13;uid=root;pwd=xxx;port=3306;Character Set=utf8;" providerName="MySql.Data.MySqlClient"/> <add name="NoEF" connectionString="database=ef_otestdb;server=192.168.107.12;uid=root;pwd=xxx;port=3306;Character Set=utf8;" providerName="MySql.Data.MySqlClient"/> </connectionStrings> <entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6"> <providers> <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider> </providers> </entityFramework> </configuration>
可以看出:
<configSections>配置節是默認生成的沒有變化。
<connectionStrings>配置節配了兩個連接字符串,並且使用<clear/>清除默認配置。
<entityFramework>配置節變化較大,數據庫客戶端為MySql.Data.MySqlClient。codeConfigurationType為MySql.Data.Entity.MySqlEFConfiguration
使用編碼配置
public class CustomDbConfiguration : MySqlEFConfiguration { public CustomDbConfiguration():base() { AddInterceptor(new CommandInterceptor(new Logger())); SetDatabaseLogFormatter((context, writeAction) => new CustomDatabaseLogFormatter(context, writeAction)); SetExecutionStrategy(MySqlProviderInvariantName.ProviderName, () => new MySqlExecutionStrategy()); } } [DbConfigurationType(typeof(CustomDbConfiguration))] public class CustomDbContext : DbContext { public CustomDbContext() : base("name=Master") { //其他代碼 } }
配置文件和編碼結合
配置文件部分
<configuration> <configSections> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/> </startup> <connectionStrings> <clear/> <!--清除默認的連接字符串,務必加上!!!--> <add name="Master" connectionString="database=ef_otestdb;server=192.168.107.13;uid=root;pwd=cnki2017;port=3306;Character Set=utf8;" providerName="MySql.Data.MySqlClient"/> <add name="NoEF" connectionString="database=ef_otestdb;server=192.168.107.13;uid=root;pwd=cnki2017;port=3306;Character Set=utf8;" providerName="MySql.Data.MySqlClient"/> </connectionStrings> <entityFramework> <providers> <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider> </providers> </entityFramework> </configuration>
編碼部分
public class CustomDbConfiguration : MySqlEFConfiguration { public CustomDbConfiguration():base() { //AddInterceptor(new CommandInterceptor(new Logger())); SetDatabaseLogFormatter((context, writeAction) => new CustomDatabaseLogFormatter(context, writeAction)); //SetExecutionStrategy(MySqlProviderInvariantName.ProviderName, () => new MySqlExecutionStrategy()); } } [DbConfigurationType(typeof(CustomDbConfiguration))] public class CustomDbContext : DbContext { public CustomDbContext() : base("name=Master") { //this.Configuration.LazyLoadingEnabled = false; //new DropCreateDatabaseIfModelChanges<CustomDbContext>() //new DropCreateDatabaseAlways<CustomDbContext>() Database.SetInitializer<CustomDbContext>(null); this.Database.Log = Log; } }