I’ve a very simple class that I’ve added method GetConnectionString(). After adding it whenever any value is accesses from the Settings class it throws an exception The type initializer for 'NameSpace.Settings' threw an exception. As soon as I remove GetConnectionString() program works fine.
using System.Data.EntityClient;
using System.Data.SqlClient;
namespace CRM {
static class Settings {
public static bool userAuthenticated = false;
public static string userGroup = "";
public static Klienci currentlySelectedClient;
public static string sqlDataConnectionDetailsCRM = GetConnectionString();
public static string GetConnectionString() {
string connection = "";
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder.InitialCatalog = dbInitialCatalog;
sqlBuilder.DataSource = dbServer;
sqlBuilder.IntegratedSecurity = false;
sqlBuilder.UserID = dbUserName;
sqlBuilder.Password = dbPasswWord;
sqlBuilder.MultipleActiveResultSets = true;
EntityConnectionStringBuilder entity = new EntityConnectionStringBuilder();
entity.Metadata = @"res://*/Data.System.csdl|res://*/Data.System.ssdl|res://*/Data.System.msl";
entity.Provider = "System.Data.SqlClient";
entity.ProviderConnectionString = sqlBuilder.ToString();
connection = entity.ToString();
return connection;
}
}
}
If I comment out sqlBuilder and entity. It works fine..
public static string GetConnectionString() {
string connection = "";
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
//sqlBuilder.InitialCatalog = dbInitialCatalog;
//sqlBuilder.DataSource = dbServer;
//sqlBuilder.IntegratedSecurity = false;
//sqlBuilder.UserID = dbUserName;
//sqlBuilder.Password = dbPasswWord;
//sqlBuilder.MultipleActiveResultSets = true;
EntityConnectionStringBuilder entity = new EntityConnectionStringBuilder();
//entity.Metadata = @"res://*/Data.System.csdl|res://*/Data.System.ssdl|res://*/Data.System.msl";
//entity.Provider = "System.Data.SqlClient";
//entity.ProviderConnectionString = sqlBuilder.ToString();
connection = entity.ToString();
return connection;
}
What’s going on? It seems fine to me..
Edit:
InnerException:
exception = “System.ArgumentNullException: Value cannot be
null.\r\nParameter name: Initial Catalog\r\n at
System.Data.SqlClient.SqlConnectionStringBuilder.set_InitialCatalog(String
value)\r\n at CRM.Settings.GetConnectionString() in
C:\Projects\Project.C.S…
While public static string dbInitialCatalog = "BazaCRM"; is set in Settings class.
The order of the fields being initialized is not guaranteed. What’s going on here is that the
sqlDataConnectionDetailsCRMis being initialized before thedbInitialCatalogfield.If you change those other static fields to be
constit should fix it.Or a better way might be to just removed your public static field, and retrieve the connection string from the method, or you might also like to investigate the
Lazy<T>class, and use that to build the connection string the first time it’s needed.