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
I am planning on SqlBulkCopy(alternative could also be Sproc with table value parameter but that's not the scope of my current question)
as the method accepts either a DataTable
or 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
question is could it be done somehow ?
Update
public struct tblCarOb
{
public String Model;
public Int32 Year;
}
EntityFrameWork
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);
}
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.