将WCF与SQL结合到MVC中

时间:2012-08-02 09:19:02

标签: asp.net-mvc-3 wcf sqldatareader

我在运行时收到此错误:

  

System.InvalidOperationException:ExecuteReader:Connection属性   尚未初始化。

指向这一行:

SqlDataReader openBuyers = b.ExecuteReader();

我正在使用我的WCF中的方法。

这是关于svc:

public string ConnectionString()
    {
        string connectToDB = ConfigurationManager.ConnectionStrings["connection"].ToString();
        return connectToDB;
    }

    public SqlConnection OpenConnection()
    {
        try
        {
            SqlConnection linkToDB = new SqlConnection(ConnectionString());
            linkToDB.Open();
            return linkToDB;
        }
        catch (Exception)
        {
            return null;
        }
    }

将此添加到我在WCF中的web.config:

<connectionStrings>
     <add name="connection" connectionString="Data 
     Source=localhost\SQLEXPRESS;Integrated Security=true;Initial
     Catalog=ProductDB"/>
</connectionStrings>

1 个答案:

答案 0 :(得分:1)

   SqlConnection myConnection = new SqlConnection(myConnectionString);
   SqlCommand myCommand = new SqlCommand(mySelectQuery, myConnection);
   myConnection.Open();
   SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

您错过了前三行 - 没有创建或打开您的连接

来源:http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executereader(v=vs.71).aspx