Entity Framework 小知識(二)

零、基於代碼配置

基於代碼配置是EF6新增的一個特性,操做步驟以下:數據庫

  1. 建立DbConfig派生類;
  2. 配置默認鏈接工廠;
  3. 設置Database Provider
  4. 設置數據庫初始化器;
1. 建立DbConfig派生類
public class EF6Config:DbConfiguration
{
    public EF6Config(){}
}

接下來使用 DbConfigurationType 屬性在上下文類中設置基於代碼的配置類:ide

[DbConfigurationType(typeof(EF6Config))]
public partial class EF6DbContext:DbContext
{
  public EF6DbContext():base("name=EF6DbContext"){}  
}
2. 配置默認鏈接工廠

使用 SetDefaultConnectionFactory 方法設置默認鏈接工廠(以SQL SERVER 數據庫爲例):this

public class EF6Config:DbConfiguration
{
    public EF6Config()
    {
      this.SetDefaultConnectionFactory(new System.Data.Entity,Infrastructure.SqlConnectionFactory());
    }
}
3. 設置Database Provider

使用 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);
    }
}
4. 設置數據庫初始化器

在使用 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 中的設置。
相關文章
相關標籤/搜索