实体框架Web配置文件

时间:2012-05-23 07:42:29

标签: asp.net asp.net-mvc entity-framework

此代码可以正常工作:

<connectionStrings>
    <add name="EFDbContext" connectionString="Data Source=.\SQLEXPRESS; Initial Catalog=myDB;Integrated Security=SSPI;
 " providerName="System.Data.SqlClient" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="Data Source=.\SQLEXPRESS; Integrated Security=True; MultipleActiveResultSets=True" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>

但此代码不起作用:

<connectionStrings>
    <add name="EFDbContext" connectionString="Data Source=.\MSSQLSERVER2008; Initial Catalog=myDb;Integrated Security=SSPI;User ID=useradmin; Password=pass; " providerName="System.Data.SqlClient" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="Data Source=.\MSSQLSERVER2008; Integrated Security=True; MultipleActiveResultSets=True" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>

第二个代码必须在具有MSQSERVER2008实例的远程服务器上运行,并且在加载页面时,将显示以下消息:

  

从数据库获取提供程序信息时发生错误。这可能是由实体框架使用不正确的连接字符串引起的。检查内部异常以获取详细信息,并确保连接字符串正确。

3 个答案:

答案 0 :(得分:11)

问题在于Integrated Security参数。当它设置为True时,如果您指定用户和密码,.Net会尝试打开与当前用户事件的连接。因此,要打开与特定用户的连接,请将Integrated Security设置为False,它将起作用。

<connectionStrings>
    <add name="EFDbContext" connectionString="Data Source=.\MSSQLSERVER2008; Initial Catalog=myDb;Integrated Security=SSPI;User ID=useradmin; Password=pass; " providerName="System.Data.SqlClient" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="Data Source=.\MSSQLSERVER2008; Integrated Security=False; MultipleActiveResultSets=True" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>

答案 1 :(得分:1)

以下是使用动态连接字符串设置进行EF连接所需要做的事情,虽然我的设置是用户输入,而不是web配置:

        // Set the properties for the data source.
        sqlBuilder.ConnectionString = "Integrated Security=SSPI;";
        sqlBuilder.DataSource = serverName;
        sqlBuilder.InitialCatalog = databaseName;
        sqlBuilder.ConnectTimeout = 60;
        sqlBuilder.MultipleActiveResultSets = true;
        if(!string.IsNullOrEmpty(userName) || !string.IsNullOrEmpty(password))
        {
            sqlBuilder.UserID = userName;
            sqlBuilder.Password = password;
            //sqlBuilder.IntegratedSecurity = false;
        }
        else
        {
            sqlBuilder.IntegratedSecurity = true;
        }

答案 2 :(得分:0)

确保代码连接字符串中的字符串正确无误:

"Data Source=.\MSSQLSERVER2008; Initial Catalog=myDb;Integrated Security=SSPI;User ID=useradmin; Password=pass;" 

检查你的sql server。