2013-07-11 135 views
0

我用linq讀取XML文件並創建對象列表。批量插入SQL Server與LINQ

StringReader stream=new StringReader(xml); 
XmlTextReader reader=new XmlTextReader(stream); 

XElement req = XElement.Load(reader); 
var users= (req.Descendants("Report") 
      .Select(e => new { 
      Fname= e.Descendants("firstName").FirstOrDefault().Value, 
      Lname = e.Descendants("lastName").FirstOrDefault().Value, 
      personalId = e.Descendants("id").FirstOrDefault().Value, 
      })).ToList(); 

用戶值包括100,000個對象。

我想批量插入這些對象到數據庫表中。

+5

這是個好主意。如果您遇到問題,請隨時回來並提出具體問題。 – nvoigt

+1

批量插入在LINQ中是不可能的,您應該通過存儲過程發送XML並將其解析到SP中。否則,InsertOnSubmit將耗費大量時間,因爲對於每一行,每個調用都將被髮送到SQL服務器。 –

回答

1
public static void saveData<T>(ref List<T> list, string destinationTableName, int batchSize) 
{ 
    using (EntityDataReader<T> reader = new EntityDataReader<T>(list)) 
    using (System.Data.SqlClient.SqlBulkCopy sbc = new System.Data.SqlClient.SqlBulkCopy("your connection string")) 
    { 
     for (int i = 0; i < reader.FieldCount; i++) 
     { 
      string colName = reader.GetName(i); 
      sbc.ColumnMappings.Add(colName, colName); 
     } 
     sbc.BatchSize = batchSize; 
     sbc.DestinationTableName = destinationTableName; 
     sbc.WriteToServer(reader); 
    } 
} 

我使用這個代碼插入項目的一個非常大的名單,T應該是一個已知的實體對象