我创建了一个静态实用程序类来简化对db的访问,并在运行我的代码“TypeInitializationException”时收到以下异常。
<connectionStrings>
<add name="vistConnectionString" connectionString="XXXXX"/>
</connectionStrings>
static class DBUtility
{
private static string dbConnection = ConfigurationManager.ConnectionStrings["vistConnectionString"].ConnectionString;
public static string DbConnection
{
get { return dbConnection; }
}
}
如果我调用静态属性,那么我会收到一个TypeInitializationException异常
string s = DBUtility.DbConnection; // this line throws the exception
来自例外的消息是
Message=The type initializer for 'VIServiceToolServiceLibrary.Database.DBUtility' threw an exception.
答案 0 :(得分:0)
使用以下代码进行连接
var connectionString = ConfigurationManager.ConnectionStrings["vistConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
try { con.Open(); }