Assuming DataTableHelper.ToDataTable()
can handle a list of Person
/Address
/Contact
, one way would be to create a generic method that takes the list of objects and the name of the table:
void WriteToServer<T>(List<T> objects, string tableName)
{
using (var bulk = new SqlBulkCopy(_connectionString))
{
bulk.DestinationTableName = tableName;
bulk.WriteToServer(DataTableHelper.ToDataTable(objects));
}
}
Then, you can use it like this:
WriteToServer(persons, "Person");
WriteToServer(addresses, "Address");
WriteToServer(contacts, "Contact");
And if Person
, Address
, and Contact
share the same base type (base class or an interface), then you should add a constraint to the method:
void WriteToServer<T>(List<T> objects, string tableName) where T : ISomething
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…