I'm having an issue bulk inserting a data table containing a C# DateTime
object into a SQL Server database, and keep getting the following error:
The given value of type String from the data source cannot be converted to type datetime of the specified target column
I ran a stack trace to see what the table was trying to insert (picture below)
Here's the code I'm using to parse the date
SInstance s = new SInstance {
Timestamp = DateTime.ParseExact(values[0],"yyyy-MM-dd",null),
//other property initializations
};
where
values[0] = "2018-08-08"
Most of the other answers say to manually configure the data table with the appropriate formats, but these tables are generated dynamically at run-time using class properties so hard-coding anything is out of the question. Here's the code for the bulk copy snippet
DataTable dt = DBOHelper.GenerateDataTable(dbObjects);
using (SqlBulkCopy sqlBulk = _database.BulkCopySQL())
{
sqlBulk.DestinationTableName = table;
sqlBulk.BatchSize = commitBatchSize;
try
{
sqlBulk.WriteToServer(dt);
dt.Dispose();
}
catch (Exception e)
{
AuditEngine.Instance.LogError("DatabaseEngine", "SQLBulkInsert", e.Message);
return 0;
}
}
and table generator function:
public static DataTable GenerateDataTable<T>(DBOCollection<T> dBOCollection)
where T : DbObject
{
DataTable dt = GenerateEmptyDataTable<T>();
List<PropertyInfo> props = GetDBODataMemberProperties<T>();
foreach (DbObject dbo in dBOCollection)
{
DataRow row = dt.NewRow();
for (int i = 0; i < props.Count; i++)
{
row[i] = props[i].GetValue(dbo);
}
dt.Rows.Add(row);
}
return dt;
}
public static DataTable GenerateEmptyDataTable<T>()
where T : DbObject
{
DataTable dt = new DataTable();
List<PropertyInfo> properties = GetDBODataMemberProperties<T>();
foreach (PropertyInfo p in properties)
{
dt.Columns.Add(p.Name, p.PropertyType);
}
return dt;
}
Everything works fine for objects without date fields, but for some reason it throws an error with all the date formats I've tried. Thanks in advance for any suggestions.