2013-07-31 23 views
1

所以,我想更新我的项目表中的某些字段:LINQ2SQL表:表<fieldname>作为参数

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(); 
} 
+1

'keys'应该是'keysToUpdate'吗? – Khan

+0

你是对的,先生。 (但这不是问题,但我会改变它以避免混淆)谢谢! – apacay

回答

3

您可以通过设置使用反射属性值做到这一点。

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(); 
    } 
} 

这不会是解决方案的最高性能。

如果这是您需要维护的模式,我会建议您查看代码生成。

+0

你的意思是一路反思?可维护性也是一个问题,这就是为什么我一直试图避免它。尽管如此,非常感谢! – apacay

+0

我不确定你的意思是什么。我已经编辑了我的答案,以便更清楚一点。该解决方案将工作,但对于大量更新将会很慢。 – Khan

+0

我还有一个问题:'GetValue'返回'object',但'key'的'Hashtable'值是另一个'type'(它实际上与destiny key field中的类型相同)......封装进入对象和解封装去没有任何必要的铸件?或者我应该考虑一个方法? – apacay