具有连接字符串的Entity Framework DbContext构造函数

Jon*_*hon 7 entity-framework

有人可以帮我理解以下两种方法将连接字符串传递给DbContext

方法#1:

public EWebDBContextEMS() : base("mainConnectionString")
{
}
Run Code Online (Sandbox Code Playgroud)

和方法#2:

public EWebDBContextEMS() : base("name=mainConnectionString")
{
}
Run Code Online (Sandbox Code Playgroud)

该文章指出name=...将获得由设计师创建的,但我用纯测试DbContext代码,它的工作原理也是如此.

这是DbContext构造函数的意图吗?在文档中,它没有提到name=连接字符串是可接受的.

非常感谢

phi*_*ady 6

类DBContext类备注有完整的解释.
简而言之:

  • 您的第一个示例可能会导致创建一个名为"mainConnectionString"的数据库.
  • name = xxxx按名称在app.config中查找connectionStrings

某些工具确实为您添加了App.config中的条目.
您链接的在线文档准确说明了帮助的位置.

在线帮助说:

使用给定字符串构造新的上下文实例,作为将建立连接的数据库的名称或连接字符串.请参阅类备注,了解如何使用它来创建连接.

如果你去上课,你会发现一个完整的解释....

///               The connection to the database (including the name of the database) can be specified in several ways.
///             If the parameterless DbContext constructor is called from a derived context, then the name of the derived context
///             is used to find a connection string in the app.config or web.config file.  If no connection string is found, then
///             the name is passed to the DefaultConnectionFactory registered on the <see cref="T:System.Data.Entity.Database"/> class.  The connection
///             factory then uses the context name as the database name in a default connection string.  (This default connection
///             string points to .\SQLEXPRESS on the local machine unless a different DefaultConnectionFactory is registered.)
///             Instead of using the derived context name, the connection/database name can also be specified explicitly by
///             passing the name to one of the DbContext constructors that takes a string.  The name can also be passed in
///             the form "name=myname", in which case the name must be found in the config file or an exception will be thrown.
///             Note that the connection found in the app.config or web.config file can be a normal database connection
///             string (not a special Entity Framework connection string) in which case the DbContext will use Code First.
 ///             However, if the connection found in the config file is a special Entity Framework connection string, then the
 ///             DbContext will use Database/Model First and the model specified in the connection string will be used.
 ///             An existing or explicitly created DbConnection can also be used instead of the database/connection name.
 ///             A <see cref="T:System.Data.Entity.DbModelBuilderVersionAttribute"/> can be applied to a class derived from DbContext to set the
 ///             version of conventions used by the context when it creates a model. If no attribute is applied then the
 ///             latest version of conventions will be used.
Run Code Online (Sandbox Code Playgroud)