我有一個ASP.NET(3.5)頁面,允許用戶上載具有多個工作表的Excel 2003文件,並且該數據被插入到數據庫中的登臺表中。數據庫表/列到Excel工作表/列的映射在XML文件中指定。我使用LINQ to SQL將數據發送到數據庫。幫助我消除多餘的代碼
ImportTablesDataContext db = new ImportTablesDataContext();
tblImportLoan loan; // class defined by LINQ to SQL
// iterate through each row of data from the Excel worksheet called Loans
foreach (DataRow dr in _data.Tables[ExcelSheetName].Rows)
{
loan = new tblImportLoan();
// iterate through each column in the mapping for the Loans worksheet
foreach (... column in mapping for this worksheet ...)
loan.GetType().GetProperty(column.DBName).SetValue(loan, GetValue(column, dr), null);
db.tblImportLoans.InsertOnSubmit(loan);
}
我重複了這5個工作表中的每一個的大部分代碼。我會像遍歷映射中定義的5個表的集合 - 但我不知道如何使硬編碼的類名/方法/屬性動態(上面的第2,7和13行)。這將允許我避免在XML文件之外引用表名。
有什麼建議嗎?
編輯: 以下是我要找的......但我不知道該怎麼做線5和8
foreach (... table in mapping ...)
{
foreach (DataRow dr in _data.Tables[table.ExcelSheetName].Rows)
{
obj = new <LINQ constructor derived from table name>;
foreach (... column in mapping ...)
obj.GetType().GetProperty(column.DBName).SetValue(obj, GetValue(column, dr), null);
db.<LINQ property derived from table name>.InsertOnSubmit(obj);
}
}
我是否正確理解您有一些方法來枚舉每個工作表的列映射? – 2010-04-21 16:13:51
@jdv:是的 - 我消除了代碼,因爲它引用了我定義的託管映射信息的自定義類,我不想進一步模糊我所關心的代碼。 – Mayo 2010-04-21 16:16:12