2011-08-29 70 views
2

我可以使用LINQ這樣的表中獲取列列表通過關口列表迭代:更新實體列使用LINQ

OrderDataContext ctx = new OrderDataContext(); 
var cols = ctx.Mapping.MappingSource 
         .GetModel(typeof(OrderDataContext)) 
         .GetMetaType(typeof(ProductInformation)) 
         .DataMembers; 

這給我列的列表中,這樣我就可以做到這一點:

foreach (var col in cols) 
{ 
    // Get the value of this column from another table 
    GetPositionForThisField(col.Name); 
} 

因此,這一切工作,我可以迭代列列表並拉從另一個表中的列的值(因爲列名是另一個表中的鍵),所以我不必切換.. ..或很多,如果...然後...

現在的問題:

當我得到這些值後,如何填充實體爲了保存它?我通常會是這樣的:

ProductInformation info = new ProductInformation(); 
info.SomeField1 = val1; 
info.SomeField2 = val2; 

ctx.ProductInformation.InsertOnSubmit(info); 
ctx.SubmitChanges(); 

但如何使用相同的列集合從上面來填充在遍歷列,當是沒有這樣的事:

info["field1"].Value = val1; 

感謝。

回答

0

只需獲取要修改的對象,設置屬性並調用SubmitChanges。不需要創建一個新對象並插入它。上下文跟蹤您更改的屬性並相應地生成更新語句。在你的情況下,你可能想通過反射而不是手動設置屬性,因爲你正在從另一個表中讀取它們。

0

您需要使用反射。假設您可以從元數據中獲得PropertyInfo

PropertyInfo property = GetPropertyForThisField(col.Name); 
property.SetValue(info, val1, null);