基於代碼配置是EF6新增的一個特性,操做步驟以下:數據庫
public class EF6Config:DbConfiguration { public EF6Config(){} }
接下來使用 DbConfigurationType 屬性在上下文類中設置基於代碼的配置類:ide
[DbConfigurationType(typeof(EF6Config))] public partial class EF6DbContext:DbContext { public EF6DbContext():base("name=EF6DbContext"){} }
使用 SetDefaultConnectionFactory 方法設置默認鏈接工廠(以SQL SERVER 數據庫爲例):this
public class EF6Config:DbConfiguration { public EF6Config() { this.SetDefaultConnectionFactory(new System.Data.Entity,Infrastructure.SqlConnectionFactory()); } }
使用 SetProviderServices() 方法配置數據庫提供程序:code
public class EF6Config:DbConfiguration { public EF6Config() { this.SetDefaultConnectionFactory(new System.Data.Entity,Infrastructure.SqlConnectionFactory()); this.SetProviderServices("System.Data.SqlClient",System.Data.Entity.SqlServer.SqlProviderServices.Instance); } }
在使用 code first 的狀況下,可使用基於代碼的配置數據庫的初始值:it
public class EF6Config:DbConfiguration { public EF6Config() { this.SetDefaultConnectionFactory(new System.Data.Entity,Infrastructure.SqlConnectionFactory()); this.SetProviderServices("System.Data.SqlClient",System.Data.Entity.SqlServer.SqlProviderServices.Instance); this.SetDatabaseInitializer<EF6DbContext>(new CustomDBInitializer(EF6DbContext)()); } }
注:.config 中 <entityframework> 的配置優於代碼配置,也就是說,若是同時在 .config 中和代碼中都設置了配置選項,則優先使用 .config 中的設置。