Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

c# - How to create a method which takes generic list and string parameter with mapping?

I have this C# working code now.

using (var bulk = new SqlBulkCopy(_connectionString))
{
    bulk.DestinationTableName = "Person";
    bulk.WriteToServer(DataTableHelper.ToDataTable(persons));
}

The problem is that the above code only applies to one table and one list object. But I have 3 more different tables and different lists that use the same code above.

Example

TableName List Object
Person persons
Address address
Contact contact
question from:https://stackoverflow.com/questions/65947258/how-to-create-a-method-which-takes-generic-list-and-string-parameter-with-mappin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...