基于代码配置是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 中的设置。