zoukankan      html  css  js  c++  java
  • Entity Framework—配置文件设置

    Entity Framework—配置文件设置

    可以使用配置文件或代码(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;
            }
    }
  • 相关阅读:
    apns libcurl
    apns libcurl
    epoll
    epoll
    Linux服务器压测
    Linux服务器压测
    libevent
    libevent
    shell脚本
    shell脚本
  • 原文地址:https://www.cnblogs.com/grj001/p/12223672.html
Copyright © 2011-2022 走看看