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;
}
}
Entity Framework——配置文件设置的更多相关文章
- Entity framework 配置文件,实现类,测试类
配置文件信息App.config: 数据库IP地址为192.168.2.186 ,数据库名为 Eleven-Six , 用户名 123456,密码654321 <?xml version=&qu ...
- Entity Framework 实践系列 —— 搞好关系 - 单相思(单向一对一,one-to-one)【转】
原以为躲入代码世界,就可以不用搞关系,哪知“关系无处不在”.写代码多年之后,终于明白“面向对象的关键是搞好对象之间的关系”.而Entity Framework作为ORM中的明日之星,首当其冲的使命就是 ...
- Entity Framework 6连接Postgresql、SQLite、LocalDB的注意事项和配置文件
Postgresql Postgresql支持Code First的方式自动生成表,不过默认的模式是dbo而不是public,而且还可以自动生成自增主键. <?xml version=" ...
- 《Entity Framework 6 Recipes》中文翻译系列 (14) -----第三章 查询之查询中设置默认值和存储过程返回多结果集
翻译的初衷以及为什么选择<Entity Framework 6 Recipes>来学习,请看本系列开篇 3-6在查询中设置默认值 问题 你有这样一个用例,当查询返回null值时,给相应属性 ...
- Oracle + Entity Framework 更新没有设置主键的表
最近用Entity Framework 开发的时候,发现一个问题,在默认情况下,EF不能对一个没有主键的表进行更新.插入和删除的动作. 那么,应该怎么处理没有主键的表呢? 我们打开这个表的edmx文件 ...
- 关于Entity Framework更新的几种方式以及可能遇到的问题(附加类型“Model”的实体失败,因为相同类型的其他实体已具有相同的主键值)在使用 "Attach" 方法或者将实体的状态设置为 "Unchanged" 或 "Modified" 时如果图形中的任何实体具有冲突键值,则可能会发生上述行为
在日常使用Entity Framework中,数据更新通常会用到.下面就简单封装了一个DBContext类 public partial class EFContext<T> : DbCo ...
- 关于使用Entity Framework时遇到的问题 未找到具有固定名称“System.Data.SqlClient”的 ADO.NET 提供程序的实体框架提供程序。请确保在应用程序配置文件的“entityFramework”节中注册了该提供程序
问题描述: 使用Entity Framework获取数据时报以下错误: 未找到具有固定名称“System.Data.SqlClient”的 ADO.NET 提供程序的实体框架提供程序.请确保在应用程序 ...
- Entity Framework 使用Mysql的配置文件
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSec ...
- Entity Framework教程(第二版)
源起 很多年前刚毕业那阵写过一篇关于Entity Framework的文章,没发首页却得到100+的推荐.可能是当时Entity Framework刚刚发布介绍EF的文章比较少.一晃这么多年过去了,E ...
随机推荐
- 爬取知名社区技术文章_items_2
item中定义获取的字段和原始数据进行处理并合法化数据 #!/usr/bin/python3 # -*- coding: utf-8 -*- import scrapy import hashlib ...
- JS题目
1.请你谈谈Cookie的弊端 cookie虽然在持久保存客户端数据提供了方便,分担了服务器存储的负担,但还是有很多局限性的. 第一:每个特定的域名下最多生成20个cookie 1.IE6或更低版本最 ...
- CColor类封装
CColor类封装 Color.h #pragma once #include <sstream> #include <string> using namespace std; ...
- javaweb后台转码
为什么需要转码? 客户端向服务器发送请求的四种情况:1.URL方式直接访问;2.页面链接(属于get请求);3.表单get提交;4.表单post提交 1.url(url和页面链接):各大浏览器.各个操 ...
- linkin大话java
青春不灭,理想犹存,linkin--勿忘初心! 不知不觉已经和java并肩作战将近了2年,在这2年之中模模糊糊研究了java2ee领域的好多东西,但是都没有做系统的整理.以前写的笔记也是零零散散不成一 ...
- tp5无法隐藏index.php入口文件
一: 官方文件: <IfModule mod_rewrite.c> Options +FollowSymlinks -Multiviews RewriteEngine on Rewrite ...
- android新建项目
MinMum Required SDK :最低支持的Android api的版本,你的应用不能在低于这个版本的手机上面运行 Target SDK:你的应用最高支持android api版本 Compi ...
- 准备:新V8即将到来,Node.js的性能正在改变
V8的Turbofan的性能特点将如何对我们优化的方式产生影响 审阅:来自V8团队的Franziska Hinkelmann和Benedikt Meurer. **更新:Node.js 8.3.0已经 ...
- 如何学习java
1.打牢基础 千里之行始于足下,只有牢固的基础才能走的更远,现在大公司越来越看中一个人的基础如何,他们看中的是你未来的发展潜力,有足够好的基础素养才能实现更多的可能. 2.多敲多练 说实话,光去看代码 ...
- linux下磁盘占用达到100%了,找不到哪些大文件耗尽了磁盘
Linux下的根分区使用率100%,但是查看/分区下的目录都不大,没有占用满,这该怎么处理? 重启是肯定有效的,目前处理情况:重新restart应用后,空间释放出来 1.lsof | grep del ...