帮助我消除多余的代码
我有一个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);
}
}
我认为你可以做到这一点通过检索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>();
这是接近你在找什么?如果不是,请添加评论。
谢谢达米安!我尝试了这一点,它的工作原理 - 必须通过添加“where TableEntity:class,new()”来调整方法声明。感谢您的建议。我会看看我能否找到一种使用字符串来派生类型的方法 - 如果有效,我会成为estatic。 – Mayo 2010-04-21 21:49:40
看起来像今天我的一天...我可以循环LINQ定义的表格 - 如果我在XML映射数据中找到匹配项,我会将该表格的类型称为DoWorkFor。理论上。关键是db.Mapping.GetTables()。 – Mayo 2010-04-21 21:56:58
酷!很高兴它是有用的。 – 2010-04-21 22:01:19
我是否正确理解您有一些方法来枚举每个工作表的列映射? – 2010-04-21 16:13:51
@jdv:是的 - 我消除了代码,因为它引用了我定义的托管映射信息的自定义类,我不想进一步模糊我所关心的代码。 – Mayo 2010-04-21 16:16:12