特定のコードが存在するかどうかをデータベースに確認する必要があるアプリケーションがあります。存在する場合は、そのコードの対応する値をロードする必要があります。それ以外の場合は null を返します。
コードごとにデータベースにヒットしたくありません(約200.000コードを実行しています)。
だから私はapp.confをテストするためにこの小さなアプリを手に入れました
public static void setAppSetting(string key, string value)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location);
if (config.AppSettings.Settings != null)
{
config.AppSettings.Settings.Remove(key);
}
config.AppSettings.Settings.Add(key, value);
config.Save(ConfigurationSaveMode.Modified);
}
public static string getAppSetting(string key)
{
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location);
return config.AppSettings.Settings[key].ToString();
}
catch (Exception ex)
{
throw ex;
}
}
private static void loadKeysValues()
{
using (SqlConnection Gcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ConnectionString))
{
//Open Connection
Gcon.Open();
using (SqlCommand sqlCmd = new SqlCommand("SELECT key,value FROM tables", Gcon))
{
using (SqlDataReader reader = sqlCmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
System.Console.WriteLine(reader.GetString(0) + " , " + reader.GetString(1));
setAppSetting(reader.GetString(0), reader.GetString(1));
}
}
} // End of SqlDataReader
} // end of SqlCommand
}
}
static void Main(string[] args)
{
System.Console.WriteLine("Loading.........");
loadKeysValues();
System.Console.WriteLine("Completed");
System.Console.WriteLine("Input a key to get its value");
var input = System.Console.Read().ToString();
System.Console.WriteLine(getAppSetting(input));
System.Console.ReadLine();
}
しかし、次の行の getAppSetting() でエラーが発生しました。
return config.AppSettings.Settings[key].ToString();
エラー: オブジェクト参照がオブジェクトのインスタンスに設定されていません。
助けてください