[英]How to create a method which takes generic list and string parameter with mapping?
I have this C# working code now.我现在有这个 C# 工作代码。
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.问题是上面的代码只适用于一表一列表object。 But I have 3 more different tables and different lists that use the same code above.
但是我还有 3 个不同的表和不同的列表,它们使用上面的相同代码。
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.我没有将代码复制 3 次,而是创建了一个带有参数的方法。
How can I achieve that using a Tuple, a dictionary, or a generic, since there are only two values and map is needed?我如何使用元组、字典或泛型来实现这一点,因为只有两个值并且需要 map?
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:假设
DataTableHelper.ToDataTable()
可以处理Person
/ Address
/ Contact
列表,一种方法是创建一个获取对象列表和表名称的通用方法:
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:如果
Person
、 Address
和Contact
共享相同的基本类型(基本 class 或接口),那么您应该在方法中添加一个约束:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.