2013-07-11 136 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应该是一个已知的实体对象