zoukankan      html  css  js  c++  java
  • Entity Framework 小知识(二)

    零、基于代码配置

    基于代码配置是EF6新增的一个特性,操作步骤如下:

    1. 创建 DbConfig 派生类;
    2. 配置默认连接工厂;
    3. 设置 Database Provider
    4. 设置数据库初始化器;
    1. 创建 DbConfig 派生类
    public class EF6Config:DbConfiguration
    {
        public EF6Config(){}
    }
    
    

    接下来使用 DbConfigurationType 属性在上下文类中设置基于代码的配置类:

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

    使用 SetDefaultConnectionFactory 方法设置默认连接工厂(以SQL SERVER 数据库为例):

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

    使用 SetProviderServices() 方法配置数据库提供程序:

    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 的情况下,可以使用基于代码的配置数据库的初始值:

    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 中 的配置优于代码配置,也就是说,如果同时在 .config 中和代码中都设置了配置选项,则优先使用 .config 中的设置。

  • 相关阅读:
    【t034】Matrix67的派对
    【t042】炮击坦克
    Multiple address space mapping technique for shared memory wherein a processor operates a fault handling routine upon a translator miss
    阿里云平台
    OpenShift:外国的免费云平台
    注册亚马逊云服务
    腾讯云
    微信公众号免费进行开发者中心云服务器配置
    消息的接收与响应
    那个学完这个小程序创业课程的小白现在月入17万
  • 原文地址:https://www.cnblogs.com/gangzhucoll/p/12778209.html
Copyright © 2011-2022 走看看