场景, 网站用户的个性化配置较多, 而且容易发生增加和改变, 如何在数据库保存是个问题.
为了避免数据库表字段经常变更, 我们设计在表增加一个varbinary(max)字段存储个性化配置.
个性化的配置则存储到dictionary<string,string>中. 然后序列化成bytes即可.
见代码
先来一个帮助类
///
public class ModelSetting
{ private Dictionary _hash;
public ModelSetting() {
_hash = new Dictionary();
} ///
///
public void Load(byte[] bytes)
{
using (MemoryStream ms1 = new MemoryStream(bytes)) {
BinaryFormatter bf = new BinaryFormatter();
_hash = (Dictionary)bf.Deserialize(ms1);
}
}
///
///
public byte[] ToByteArray()
{
using (MemoryStream ms1 = new MemoryStream())
{
BinaryFormatter b = new BinaryFormatter();
b.Serialize(ms1, _hash);
return ms1.ToArray();
}
} public ICollection Keys
{
get
{
return _hash.Keys;
}
} public string Get(string Name, string Def){
if (_hash.ContainsKey(Name))
return _hash[Name];
else
return Def;
}
public void Set(string Name, string Val)
{
if (Val == null)
Val = "";
_hash[Name] = Val;
}
}
然后在domain中的模型中增加如下代码
///
protected ModelSetting modelsetting = new ModelSetting();
private Dictionary _allSettings = new Dictionary();
private bool _isLoaded = false;
///
public Dictionary AllSettings
{
get {
if (!_isLoaded)
LoadSettings();
return _allSettings;
}
} ///
private void LoadSettings()
{
if (Settings != null && Settings.Length > 1)
{
modelsetting.Load(Settings); _allSettings.Clear();
foreach (string key in modelsetting.Keys)
{
_allSettings.Add(key, modelsetting.Get(key, string.Empty));
} _isLoaded = true;
}
}
///
///
///
public void SetOneSetting(string key, string value)
{
if (AllSettings.ContainsKey(key))
{
AllSettings[key] = value;
}
else
{
AllSettings.Add(key, value);
}
}
public void SaveSetting()
{
foreach (string key in _allSettings.Keys)
{
modelsetting.Set(key, _allSettings[key]);
}
Settings = modelsetting.ToByteArray();
}
存储和取值
public ActionResult TestModelSetting() {
var temp = _userservice.Table.First();
temp.SetOneSetting("xiaomi", "jianjialin");
temp.SetOneSetting("mobile","13900000000");
temp.SaveSetting();
_userservice.Update(temp); var temp2 = _userservice.Table.First();
return Content(temp2.AllSettings["xiaomi"]);
}