zoukankan      html  css  js  c++  java
  • 【译】第38节---EF6-基于代码的配置

    原文:http://www.entityframeworktutorial.net/entityframework6/code-based-configuration.aspx

    EF6引入了基于代码的配置。你仍可以使用以前在app.config的<entityframework>节点中配置的代码来配置Entity Framework相关设置。

    但是,app.config优先于基于代码的配置。 换句话说,如果在代码和配置文件中都设置了配置选项,则使用配置文件中的设置。

    我们来看看如何使用Entity Framework 6实现基于代码的配置。

    首先,需要创建一个派生DbConfiguration(System.Data.Entity.DbConfiguration)类的新类:

    public class FE6CodeConfig : DbConfiguration
    {
        public FE6CodeConfig()
        {
            //define configuration here
        }
    }

    现在,可以在配置文件中设置codeConfigurationType,如下所示:

    <entityFramework codeConfigurationType="EF6DBFirstTutorials.FE6CodeConfig, EF6DBFirstTutorials">
    </entityFramework>

    或者可以使用上下文类中的DbConfigurationType属性来设置基于代码的配置类:

    注意:EF不支持在同一AppDomain中使用多个配置类。 如果使用此属性为两个上下文设置不同的配置类,则会抛出异常。

    现在,可以在构造函数中使用DbConfiguration的不同方法,如下所示:

    让我们看看如何使用基于代码的配置以及配置文件进行不同的设置。

    设置默认连接工厂

    基于代码的配置:

    public class FE6CodeConfig : DbConfiguration
        {
            public FE6CodeConfig()
            {
                this.SetDefaultConnectionFactory(new System.Data.Entity.Infrastructure.SqlConnectionFactory());
            }
        }

    基于配置文件:

    <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    </entityFramework>

    设置数据库Provider

    基于代码的配置:

    public class FE6CodeConfig : DbConfiguration
    {
        public FE6CodeConfig()
        {
        this.SetProviderServices("System.Data.SqlClient", 
                    System.Data.Entity.SqlServer.SqlProviderServices.Instance);
        }
    }

    基于配置文件:

    <entityFramework>
        <providers>
            <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
        </providers>
        </entityFramework>

    设置数据库初始化

    基于代码的配置:

    public class FE6CodeConfig : DbConfiguration
        {
            public FE6CodeConfig()
            {
                this.SetDatabaseInitializer<SchoolDBEntities>(new CustomDBInitializer<SchoolDBEntities>());
            }
        }

    基于配置文件:

    <entityFramework>
        <contexts>
            <context type="EF6DBFirstTutorials.SchoolDBEntities, EF6DBFirstTutorials"  >
            <databaseInitializer   type="EF6DBFirstTutorials.CustomDBInitializer , EF6DBFirstTutorials">
            </databaseInitializer>
            </context>
        </contexts>    
        </entityFramework>
  • 相关阅读:
    最短路必经点(边)
    [HNOI2008]越狱
    【模版】卢卡斯定理
    偶数
    [USACO17FEB]Why Did the Cow Cross the Road I S
    [USACO17FEB]Why Did the Cow Cross the Road II S
    [USACO07NOV]电话线Telephone Wire
    [JSOI2007]祖码Zuma
    单人纸牌_NOI导刊2011提高(04)
    [USACO13OPEN]重力异常
  • 原文地址:https://www.cnblogs.com/talentzemin/p/7380690.html
Copyright © 2011-2022 走看看