[英]C# complex class to SQLBulkInsert millions or rows
我有一個問題,顯然很簡單,但我沒有找到任何相關的東西。
public class Fruit
{
public string name { get; set; }
public string color { get; set; }
public string shape { get; set; }
public Image image { get; set; }
}
public class Image
{
public string Id { get; set; }
public string URL { get; set; }
}
那是我的“復雜”class,我想將其轉換為 DataTable 以應用 SQLBulkCopy,但是當它檢索圖像 class 時,它不會帶來值,而是會引發異常的數據類型“圖像”。
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
關於如何檢索 Image 屬性的 ID 以執行 SQLBulkCopy 的任何線索?
順便說一句,這是我用於插入的方法:
public static void SaveToDatabase(DataTable data)
{
using (var connection = new SqlConnection(dbConn))
{
SqlTransaction transaction = null;
connection.Open();
try
{
transaction = connection.BeginTransaction();
using (var sqlBulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, transaction))
{
sqlBulkCopy.DestinationTableName = "Fruit";
sqlBulkCopy.ColumnMappings.Add("name", "name");
sqlBulkCopy.ColumnMappings.Add("color", "color");
sqlBulkCopy.ColumnMappings.Add("shape", "shape");
sqlBulkCopy.ColumnMappings.Add("image", "image");
sqlBulkCopy.WriteToServer(data);
}
transaction.Commit();
}
catch (Exception ex) // Here I got the datatype Exception because I don't know how to get the Image.ID value
{
transaction.Rollback();
}
}
}
顯然我的帖子有點混亂,所以我將在這里添加問題:
如何從以下代碼中的圖像class中獲取URL和ID值? 目前,它帶來了未知並引發異常的 object 圖像
sqlBulkCopy.ColumnMappings.Add("image", "image");
我怎么能 map 他們? 我知道我可以逐行執行,但每次執行時我有超過 200 萬行要處理。 這就是我嘗試使用批量復制的原因。
我需要補充一點,這些數據來自 Json 格式的 API 調用
在修改代碼進行測試后,我確實找到了解決方案:
if (prop.GetChildProperties().Count > 1)
row[prop.Name] = (Image)prop.GetValue(item);
else
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
解決方案只是將 GetValue 轉換為 Image class,這適用於 ToDataTable 方法:
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
if (prop.GetChildProperties().Count > 1)
row[prop.Name] = (Image)prop.GetValue(item);
else
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
謝謝大家的時間和幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.