连接字符串参数名称=

时间:2015-03-05 09:35:16

标签: visual-studio

  <connectionStrings>
<add name="MyContext" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;
  port=3306;database=mycontext;uid=root;password=********"/>

在上面的代码中,name属性表示我的上下文,而database属性也设置为mycontext。 name属性的作用是什么,我会从一些外部代码中使用它吗?我是第一次尝试创建与本地数据库的连接,我不知道我应该如何使用name属性。有人可以提供一个例子吗? 我试过google&#34; mysql connectionstring&#34; (其中)其中很少有人在connectionstring中实际拥有name属性。

我正在使用vs2013并尝试使用实体框架

建立连接字符串

1 个答案:

答案 0 :(得分:1)

name属性在那里,因此您可以根据需要从app.config或web.config中的代码或其他部分引用连接字符串。

在C#中,它可能看起来像这样:

var connectionString = ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString;

或者,如果您使用的是EntityFramework:

public class SomeContext : DbContext 
{ 
      public SomeContext() 
         : base("name=MyContext") 
      { 
      } 
}