[英]custom Object collection to SqlDataReader
I am trying to avoid using large objects in my current project, while I wish to upload collections of data to populate an SQL Server Table 我想避免在当前项目中使用大对象,而我希望上载数据集合以填充SQL Server表
I am planning on SqlBulkCopy(alternative could also be Sproc with table value parameter but that's not the scope of my current question) 我正在计划SqlBulkCopy(也可以是具有表值参数的Sproc,但这不是我当前问题的范围)
as the method accepts either a DataTable
or SqlDataReader
因为该方法接受DataTable
或SqlDataReader
I was wondering if I could do something like : 我想知道我是否可以做类似的事情:
public struct tblCarOb
{
public String Model;
public Int32 Year;
}
as i prefer structs over class objects it could be a class to. 因为我更喜欢结构而不是类对象,所以它可能是一个类。
List<tblCarOb> tcoLst = new List<tblCarOb>(){ new tblCarObj(){ Model = "A", Year= 2010 }};
using (sqlConnection ...)
{
use Reader to read form tcoLst or tblCarOb[]
}
so I could avoid using the more complex DataTable
所以我可以避免使用更复杂的DataTable
question is could it be done somehow ? 问题是可以做到吗?
Update 更新
public struct tblCarOb
{
public String Model;
public Int32 Year;
}
EntityFrameWork
不使用EntityFrameWork
DataTable
我不喜欢像DataTable
那样使用反射 the intention was to minimize overhead and performance hit. 目的是最大程度地减少开销和性能损失。
thanks in advance 提前致谢
I suggest you this code 我建议你这个代码
using (IDataReader reader = tcoLst.GetDataReader())
using (SqlConnection conn = new SqlConnection(....))
using (SqlBulkCopy bcp = new SqlBulkCopy(conn))
{
conn.Open();
//-->>>>>>>define this value
bcp.DestinationTableName = "YourTableName";
string createTableSql = string.Empty;
createTableSql += string.Format("IF EXISTS(SELECT * FROM sys.tables t WHERE t.name = {0}) DROP TABLE {0};", bcp.DestinationTableName);
createTableSql += string.Format("CREATE TABLE dbo.{0};",bcp.DestinationTableName);
for (int column = 0; column < reader.FieldCount; column++)
{
if (column > 0)
{
createTableSql += ",";
}
createTableSql += "[" + reader.GetName(column) + "]" + " VARCHAR(MAX) NULL";
}
createTableSql += ");";
using (SqlCommand createTable = new SqlCommand(createTableSql, conn))
{
createTable.ExecuteNonQuery();
}
bcp.WriteToServer(reader);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.