简体   繁体   中英

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

Instead of duplicating the code 3 times, I am creating a method which takes a parameter.

How can I achieve that using a Tuple, a dictionary, or a generic, since there are only two values and map is needed?

I tried something like below but the syntax is invalid.

var dict = new Dictionary<string, List<T>>();
dict.Add("Person", persons);
dict.Add("Address", address);
dict.Add("Contact", contact);

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

I will illustrate the method of use with an example.The example is very simple

public class Person
{
   public int ID { get; set; }
   public string PersonName { get; set; }
}
public class Address
{
   public string PersonAddress { get; set; }
}
public class StoreDataBase<T>
{
   public static void ToDataTable(T item)
   {
       using (TestDBContext db = new TestDBContext())
       {
           db.GetTable<T>().InsertOnSubmit(item);
           db.SubmitChanges();
       }
   }
}

//for use
Person person = new Person() { ID = 1, PersonName = "Meysam" };
StoreDataBase<Person>.ToDataTable(person);

Address address = new Address() { PersonAddress = "Asia" };
StoreDataBase<Address>.ToDataTable(address);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM