Linq2sql表:列表<;字段名称>;作为参数
本文关键字:gt 参数 字段 列表 lt Linq2sql | 更新日期: 2023-09-27 18:25:39
所以,我想更新我的项目表的某些字段:
internal void FieldsUpdate(string id, System.Collections.Hashtable fieldsWithChanges, List<string> keysToUpdate)
{
using (DBDataContext db = new DBDataContext())
{
item myItem = db.items.Single(t=>t.id==id);
keysToUpdate.ForEach(key => {
myItem[key] = GetValue(fieldsWithChanges, key).ToString();
//Or something like that, I'm inventing that index
});
db.SubmitChanges();
}
}
myItem[key]
不存在,那么我应该怎么做呢?
据我所知,这是一个糟糕的选择:
internal void FieldsUpdate(string id, System.Collections.Hashtable fieldsWithChanges, List<string> keysToUpdate)
{
using (DBDataContext db = new DBDataContext())
{
item myItem = db.items.Single(t=>t.id==id);
keysToUpdate.ForEach(key => {
if (key=="thisKey")
myItem.thisKey = GetValue(fieldsWithChanges, key).ToString();
// really awful. So What this condition for every colname? thats unsustainable.
});
}
db.SubmitChanges();
}
您可以通过使用反射设置属性值来实现这一点。
internal void FieldsUpdate(string id, System.Collections.Hashtable fieldsWithChanges, List<string> keysToUpdate)
{
using (DBDataContext db = new DBDataContext())
{
item myItem = db.items.Single(t=>t.id==id);
keysToUpdate.ForEach(key => {
typeof(item).GetProperty(key)
.SetValue(item, GetValue(fieldsWithChanges, key), null);
});
db.SubmitChanges();
}
}
这将不是性能最好的解决方案。
如果这是您需要维护的模式,我建议您研究代码生成。