我有一个我试图在另一个程序中使用的DLL。这是导致一些问题的部分:
来自我的dll:
public class fService
{
public static readonly string connectionString = "My connection string";
...
etc
...
public static void myStaticMethod()
{
fStat x = new fStat();
}
}
来自我的其他计划:
private void btnSave_Click(object sender, EventArgs e)
{
try
{
fService.myStaticMethod();
MessageBox.Show("Success!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
我得到的例外是The ConnectionString property has not been initialized.
。
这是为什么?如何正确初始化?将fService类定为静态(我想避免这种情况)?
堆栈跟踪:
at System.Data.SqlClient.SqlConnection.PermissionDemand()
at System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at fManager.tableClasses.fStats..ctor() in e:\fManager\project\fManager\ConsoleApplication1\tableClasses\fStats.cs:line 55
at fManager.fService.constructElement(String header, String content, fService& service) in e:\fManager\project\fManager\ConsoleApplication1\fService.cs:line 964
at fManager.fService.LoadIni(String path) in e:\fManager\project\fManager\ConsoleApplication1\fService.cs:line 675
at fManagerF.mainForm.btnSave_Click(Object sender, EventArgs e) in e:\fManager\exeProject\fManagerF\fManager\mainForm.cs:line 54
这就是问题的根源所在:
public fStat()
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("fManager.getfStats", conn);
SqlCommand cmdCount = new SqlCommand("SELECT COUNT(*) FROM [fManager].[fStats]", conn);
_id = 0;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
conn.Open();
_id = (int)cmdCount.ExecuteScalar();
cmd.ExecuteNonQuery();
conn.Close();
}
}
编辑:如果你downvote / vote关闭,请告诉我原因。我觉得我已经提供了所有信息并且我保持在topid上,但请通过让我知道我失败的地方帮助我改进=)
答案 0 :(得分:2)
您将connectionString
属性定义为fService
类的静态成员,但在connectionString
类中使用变量fStat
。这不是同一个变量。您的fService.connectionString
已初始化,fStat.connectionString
未初始化。同样,ConnectionString
中的SqlConnection
也未初始化,因此错误。