一个典型的EF应用大多数情况下是一个DbContext的派生类(derived class)来控制,通常可以使用该派生类调用DbContext的构造函数,来控制以下的东西:

(1)、上下文如何连接到数据库(给定连接字符串)

(2)、上下文是通过Code First语法计算模型还是使用EF 设计器

(3)、额外的高级选项

下面是DbContext构造器的常用的用途:

一、DbContext无参构造函数

如果当前EF应用中没有做任何的配置.且在你自定义的数据库上下文类中没有调用DbContext带参的构造函数,那么当前应用对应的数据库上下文类,将会调用DbContext的默认无参的构造函数(EF默认规定的数据库连接),代码如下:

namespace Demo.EF
{
public class EFStudyContext : DbContext
{
public EFStudyContext()// C# will call base class parameterless constructor by default
{
}
}
}

EF默认的联结字符串如下:

Data Source=(localdb)\mssqllocaldb;Initial Catalog=EFStudyConsole(项目名称).EFStudyDbContext(上下文名称);Integrated Security=True;MultipleActiveResultSets=True

EF会用上下文的完全限定名(命名空间+上下文类)作为数据库名,创建一个连接字符串,该连接字符串会连接本地的SQL Express或者LocalDb,并在SQL Express或者LocalD创建对应的数据库,如果两者都安装了,则会选择连接SQL Express。

注:VS2010默认安装SQL Express,VS2012默认安装LocalDb,在安装过程中,EF NuGet包会检查哪个数据库服务(前面介绍的)可用,当EF创建默认连接的时候,当EF创建默认链接的时候,NuGet包将通过设置默认的Code First数据库服务器来更新配置文件,该数据库服务器在通过约定创建连接时首先使用该服务器。.如果SQL Express 正在运行,它会被使用,如果它不可用,LocalDb会替代它,但是这个过程不会对配置文件做任何的更改,如果它已经包含默认连接工厂的设置.

二、DbContext带string参数的构造函数

1、如果没有在数据库上下文进行其他额外的配置,然后调用DbContext中的带参的构造函数,传入你想要使用的数据库连接字符串,然后Code First中的数据库上下文就会运行在基于当前数据库连接字符串上.代码如下:

public class BloggingContext : DbContext
{
public BloggingContext(): base("BloggingDatabase")
{}
}
Data Source=(localdb)\mssqllocaldb;Initial Catalog=BloggingDatabase;Integrated Security=True;MultipleActiveResultSets=True

2、使用app.config/web.config配置文件中的连接字符串,表示你在应用程序中已经进行了配置,这一点要区分上面的方法.

(1)、有Ado.Net使用经历的都知道,一般情况下,数据库连接字符串一般定义在app.config/web.config配置文件中,例如:

<configuration>
<connectionStrings>
<add name="BolggingContext"
providerName="System.Data.SqlServerCe.4.0"
connectionString="Data Source=Blogging.sdf"/>
</connectionStrings>
</configuration>

这在EF中相当于告诉数据库上下文去使用当前连接字符串对应的数据库服务,而不是使用SQL Express or LocalDb,数据库上下文代码如下:

public class BloggingContext : DbContext
{
public BloggingContext()
{
}
}

如果连接字符串的name属性值和上下文类名一样(either with or without namespace qualification),那么数据库上下文在执行无参构造函数的时候,会使用配置文件的连接字符串去连接数据库.

using (var context=new BloggingContext())
{
string connStr = context.Database.Connection.ConnectionString;
Console.WriteLine(connStr);
}

(2)、如果连接字符串的name属性值和上下文类名不一样,但是还是希望上下文使用配置文件的数据库连接进行数据库连接,这时就需要在上下文构造函数中调用DbContext的带string参数的构造函数,并传入连接字符串的name属性值,代码如下:

    public class BloggingContext:DbContext
{
public DbSet<User> Users { get; set; } public BloggingContext():base("BloggingStr")
{ }
}
static void Main(string[] args)
{
using (var context=new BloggingContext())
{
string connStr = context.Database.Connection.ConnectionString;
Console.WriteLine(connStr);
}
Console.ReadKey();
}

另外一种方式是传递给DbContext构造函数配置文件中的connectionString节点的name属性来指定上下文通过配置文件中connectionString来连接字符串,代码如下:

    public class BloggingContext:DbContext
{
public DbSet<User> Users { get; set; } public BloggingContext():base("name=BloggingStr")
{ }
}
static void Main(string[] args)
{
using (var context=new BloggingContext())
{
string connStr = context.Database.Connection.ConnectionString;
Console.WriteLine(connStr);
}
Console.ReadKey();
}

上面这种方式是明确EF进行数据库连接的时候去配置文件找连接字符串。

(3)、连接字符串的终极解决方案,直接给连接字符串,什么都不要配,代码如下:

    public class BloggingContext:DbContext
{
public DbSet<User> Users { get; set; } public BloggingContext():base("server=.;database=EFStudy;uid=sa;pwd=123456;")
{ }
}
static void Main(string[] args)
{
using (var context=new BloggingContext())
{
string connStr = context.Database.Connection.ConnectionString;
Console.WriteLine(connStr);
}
Console.ReadKey();
}

注:默认情况下,当前的连接字符串使用的是System.Data.SqlClilent作为provider,这里可以被改变通过做一个IConnectionFactory的不同的实现来替换context.Database.DefaultConnectionFactory默认的实现.

三、还有其他两种方法,不常用

1、You can use an existing DbConnection object by passing it to a DbContext constructor. If the connection object is an instance of EntityConnection, then the model specified in the connection will be used rather than calculating a model using Code First. If the object is an instance of some other type—for example, SqlConnection—then the context will use it for Code First mode.

使用一个DbConnection 实例,或者是SqlConnection实例或者EntityConnection实例,传递给DbContext的构造函数均可指定对应的数据库连接规则.

2、You can pass an existing ObjectContext to a DbContext constructor to create a DbContext wrapping the existing context. This can be used for existing applications that use ObjectContext but which want to take advantage of DbContext in some parts of the application.

EF 数据库连接约定(Connection String Conventions in Code First)的更多相关文章

  1. ORM系列之二:EF(4) 约定、注释、Fluent API

    目录 1.前言 2.约定 2.1 主键约定 2.2 关系约定 2.3 复杂类型约定 3.数据注释 3.1 主键 3.2 必需 3.3 MaxLength和MinLength 3.4 NotMapped ...

  2. MVC: Connection String

    背景: 之前项目使用的是DB first/Model first,现在要对EF升级的6.0,并且更换成Code first. 问题: 1. System.Data.Entity.Core.Metada ...

  3. Entity Framework Connection String不保留密码的方法

    添加Entity Data Model的时候,到最后一步,有两个radio box: 如果选择include sensitive data,虽然很方便,但是在web.config或者app.confi ...

  4. MVC模式下unity配置,报错“No connection string named '**Context' could be found in the application config file”

     写在前面: 第一次配置时好好的,后来第二次改到MVC模式,把依赖注入写成字典的单例模式时,由于新建的ORM(数据库映射模型EF),怎么弄都不用,一直报错"No connection str ...

  5. 转载 How to Encrypt connection string in web.config

    转载原地址: https://chiragrdarji.wordpress.com/2008/08/11/how-to-encrypt-connection-string-in-webconfig/ ...

  6. ASP.NET MVC 5 - 创建连接字符串(Connection String)并使用SQL Server LocalDB

    您创建的MovieDBContext类负责处理连接到数据库,并将Movie对象映射到数据库记录的任务中.你可能会问一个问题,如何指定它将连接到数据库? 实际上,确实没有指定要使用的数据库,Entity ...

  7. No connection string named '***' could be found in the application config file

    Code-First时更新数据库遇到妖孽问题“No connection string named '***' could be found in the application config fil ...

  8. How to set China Azure Storage Connection String

    Configure Visual Studio to access China Azure Storage Open Visual Studio 2012, Server Explorer Add n ...

  9. 不支持的关键字:“provider connection string”报错信息及解决方案

    今天在部署公司开发框架的时候 ,登录系统之后调用代办列表的时候就报错了 总线调用契约XX.Service.Contracts.IXXService上的GetXXCount方法时出错. Resoluti ...

随机推荐

  1. windows开启禁用网卡

    ' 在Windows中实现sudo命令--命令行环境中获取管理员权限 'ShellExecute 方法 '作用: 用于运行一个程序或脚本. '语法 ' .ShellExecute "appl ...

  2. webuploader传递参数

    实际开发过程中,比如我有个工单提交系统,提交工单的时候用webuploader上传图片,如果工单的ID是自增长类型的,那么我在上传图片的时候肯定需要关联上工单的id,这时候就需要通过webupload ...

  3. linux常见命令整理

    Linux管理文件和目录的命令 命令 功能 命令 功能 pwd 显示当前目录 ls 查看目录下的内容 cd 改变所在目录 cat 显示文件的内容 grep 在文件中查找某字符 cp 复制文件 touc ...

  4. 给IDistributedCache新增了扩展方法GetOrCreate、GetOrCreateAsync

    public static class DistributedCacheExtensions { public static TItem GetOrCreate<TItem>(this I ...

  5. Prism 的 TabControl 导航

    基于Prism 7.1 最近工作中可能会用到TabControl所以作为小菜的我提前预习了一下,结果并没有我想的那么简单,于是乎 各种网上查,本来用wpf的人就不多 prism 的可查的资料就更少的可 ...

  6. 【cocos2d-x 手游研发小技巧(6)聊天系统+字体高亮】

    转载请注明出处:http://www.cnblogs.com/zisou/p/cocos2dxJQ-6.html 聊天系统在手机网游中是最常见的交互工具,大家在一起边玩游戏边聊天岂不乐哉: 废话不多了 ...

  7. 如何使用socket进行java网络编程(五)

    本篇记录: 1.再谈readLine()方法 2.什么是真正的长连接 最近又参与了一个socket的项目,又遇到了老生常谈的readLine()问题:对方通过其vb程序向我方socketServer程 ...

  8. Day 13 迭代器,生成器.

    一.迭代器 可以进行for循环的 数据类型 str ,list tuple dict set 文件句柄 什么是可迭代对象? 方法一:dir(被测对象) 如果他含有__iter__,那这个对象就叫做可迭 ...

  9. jzoj5996

    我們可以枚舉每一個串的最短回文後綴,這樣一定不會算重. 雖然一個字符串可能會有多個回文後綴,但是答案只會在最短的後綴被計算 記f[i]表示長度為i回文串中,沒有長度>1的回文後綴的個數,將總個數 ...

  10. Brainteaser-292. Nim Game

    You are playing the following Nim Game with your friend: There is a heap of stones on the table, eac ...