2010-04-21 37 views
0

我有一個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); 
    } 
} 
+0

我是否正確理解您有一些方法來枚舉每個工作表的列映射? – 2010-04-21 16:13:51

+0

@jdv:是的 - 我消除了代碼,因爲它引用了我定義的託管映射信息的自定義類,我不想進一步模糊我所關心的代碼。 – Mayo 2010-04-21 16:16:12

回答

2

我認爲你可以做到這一點通過檢索Table<TEntity>直接來自DataContext的對象。首先,你需要用你的代碼在一個通用的方法:

public void DoWorkFor<TEntity>() 
{ 
    ImportTablesDataContext db = new ImportTablesDataContext(); 
    Table<TEntity> table = db.GetTable<TEntity>(); 

    // iterate through each row of data from the Excel worksheet called Loans 
    foreach (DataRow dr in _data.Tables[ExcelSheetName].Rows) 
    { 
     entity = new TEntity(); 

     // iterate through each column in the mapping for the Loans worksheet 
     foreach (... column in mapping for this worksheet ...) 
     { 
      entity.GetType().GetProperty(column.DBName) 
       .SetValue(entity, GetValue(column, dr), null); 
     } 

     table.InsertOnSubmit(entity); 
    } 
} 

然後,在你的程序別的地方,你需要調用此方法,並提供相應的實體類型:

DoWorkFor<tblImportLoan>(); 
DoWorkFor<tblOtherType1>(); 
DoWorkFor<tblOtherType2>(); 
DoWorkFor<tblOtherType3>(); 
DoWorkFor<tblOtherType4>(); 

這是接近你在找什麼?如果不是,請添加評論。

+0

謝謝達米安!我嘗試了這一點,它的工作原理 - 必須通過添加「where TableEntity:class,new()」來調整方法聲明。感謝您的建議。我會看看我能否找到一種使用字符串來派生類型的方法 - 如果有效,我會成爲estatic。 – Mayo 2010-04-21 21:49:40

+0

看起來像今天我的一天...我可以循環LINQ定義的表格 - 如果我在XML映射數據中找到匹配項,我會將該表格的類型稱爲DoWorkFor。理論上。關鍵是db.Mapping.GetTables()。 – Mayo 2010-04-21 21:56:58

+0

酷!很高興它是有用的。 – 2010-04-21 22:01:19