2013-07-31 20 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