Oog*_*oga 5 c# sqlite database-design initialization
我有一个使用SQLite的应用程序,它非常轻便且快速.我有一些不一定需要在启动时加载的首选项,但可能需要在不同的时间使用,具体取决于用户的去向.话虽这么说,我无法决定在哪里存储这些信息.
Q1:我应该继续将其存储在数据库中吗?我应该将它存储在配置文件中吗?
Q2:我是否应该在启动时加载和存储首选项和其他数据,即使它们不一定立即被使用?或者我应该在需要时查询数据库?
示例:我的应用程序可以存储使用该软件的公司的公司信息.公司名称,公司电话等.此信息的唯一使用时间是软件自动打印信件,或者用户在程序中编辑公司信息.
编辑:我意识到这归结为应用程序设置与用户设置.我的程序每个软件副本没有多个用户.话虽如此,我认为这些将是应用程序设置.
您可能想要做的是编写一个类来封装这些设置,然后将它们读入 Hashtable。
您可以使用一个基本的 GetSetting 方法来根据名称查找设置。如果设置位于Hashtable中,则返回值,否则去DB查找设置然后将其存储在Hashtable中。然后,您可以为所需的每个设置编写单独的属性,每个属性都调用 GetSetting/SetSetting 方法。
这使您可以轻松地将设置存储在 DB 中,并缓存读取以避免不断读取 DB。
public class Settings {
private object SyncRoot = new object();
private System.Collections.Hashtable _cache = new System.Collections.Hashtable();
public T GetSetting<T>(string xPath, T defaultValue)
{
lock (SyncRoot)
{
if (!_cache.ContainsKey(xPath))
{
T val = GetSettingFromDB<T>(xPath, defaultValue);
_cache[xPath] = val;
return val;
}
return (T)_cache[xPath];
}
}
public T GetSettingFromDB<T>(string xPath, T defaultValue)
{
// Read from DB
}
public void SaveSetting<T>(string xPath, T value)
{
lock (SyncRoot)
{
if (_cache.ContainsKey(xPath))
_cache[xPath] = value;
}
SaveSettingToDB<T>(xPath, value);
}
public T SaveSettingToDB<T>(string xPath, T defaultValue)
{
// Read from DB
}
}
Run Code Online (Sandbox Code Playgroud)
然后只需创建一个具有一堆属性的类,如下所示:
public static bool BooleanFeature
{
get { return Settings.GetSetting<bool>("BooleanFeature", true); }
set { Settings.SaveSetting<bool>("BooleanFeature", value); }
}
Run Code Online (Sandbox Code Playgroud)
现在您可以在代码中执行此操作:
if (Setting.BooleanFeature) {
// Run certain code
else {
// Run other code
}
Run Code Online (Sandbox Code Playgroud)