网站开发技巧, 使用byte[]持久化用户个性设置
场景, 网站用户的个性化配置较多, 而且容易发生增加和改变, 如何在数据库保存是个问题.
为了避免数据库表字段经常变更, 我们设计在表增加一个varbinary(max)字段存储个性化配置.
个性化的配置则存储到dictionary<string,string>中. 然后序列化成bytes即可.
见代码
先来一个帮助类
////// 持久个性化设置的类 /// public class ModelSetting { private Dictionary_hash; public ModelSetting() { _hash = new Dictionary (); } /// /// 把数据库中的bytes转化成可用的dictionary /// /// public void Load(byte[] bytes) { using (MemoryStream ms1 = new MemoryStream(bytes)) { BinaryFormatter bf = new BinaryFormatter(); _hash = (Dictionary)bf.Deserialize(ms1); } } /// /// 把实体中的dictionary转成bytes /// ///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中的模型中增加如下代码
////// Setting设置帮助类 /// protected ModelSetting modelsetting = new ModelSetting(); private Dictionary_allSettings = new Dictionary (); private bool _isLoaded = false; /// /// 通过这个访问个性化设置 /// public DictionaryAllSettings { 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; } } ////// 将单一的某个设置的键值对,存入网站本身二进制的Setting里. /// 本方法只是临时将键值对,放入字典。真正更新数据库,还需要SaveSetting()再Update(YibuSite) /// /// /// 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"]); }
本人在长沙, 有工作可以加我QQ4658276