Class Properties Or List Class XML Serialization And Bulk Insert Using C# And SQL Server

The objective of this blog is to implement bulk insert / update data from UI or Business Layers where most of the time, we use looping to insert data. For this scenario, we can convert class or List Collection into XML format. The useful thing that we need most of the times is serialization which I will implement here for generating XML.

In most of the cases, I have seen that the easiest way to convert to XML is by using the DataTable.
  1. private static string ConvertDataTableToXML(DataTable dtData) {  
  2.     DataSet dsData = new DataSet();  
  3.     StringBuilder sbSQL;  
  4.     StringWriter swSQL;  
  5.     string XMLformat;  
  6.     try {  
  7.         sbSQL = new StringBuilder();  
  8.         swSQL = new StringWriter(sbSQL);  
  9.         dsData.Merge(dtData, true, MissingSchemaAction.AddWithKey);  
  10.         dsData.Tables[0].TableName = "SampleDataTable";  
  11.         foreach(DataColumn col in dsData.Tables[0].Columns) {  
  12.             col.ColumnMapping = MappingType.Attribute;  
  13.         }  
  14.         dsData.WriteXml(swSQL, XmlWriteMode.WriteSchema);  
  15.         XMLformat = sbSQL.ToString();  
  16.         return XMLformat;  
  17.     } catch (Exception sysException) {  
  18.         throw sysException;  
  19.     }  
  20. }  
After converting any DataTable, we will get the below string.
  1. <NewDataSet>  
  2.     <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">  
  3.         <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">  
  4.             <xs:complexType>  
  5.                 <xs:choice minOccurs="0" maxOccurs="unbounded">  
  6.                     <xs:element name="SampleDataTable">  
  7.                         <xs:complexType>  
  8.                             <xs:attribute name="Name" type="xs:string" />  
  9.                             <xs:attribute name="Address" type="xs:string" />  
  10.                             <xs:attribute name="Phone" type="xs:string" /> </xs:complexType>  
  11.                     </xs:element>  
  12.                 </xs:choice>  
  13.             </xs:complexType>  
  14.         </xs:element>  
  15.     </xs:schema>  
  16.     <SampleDataTable Name="Franklin" Address="Hosur" Phone="46945616" />  
  17.     <SampleDataTable Name="SAMRAj Gill" Address="DT-HOSUR" Phone="78971651" />   
  18. </NewDataSet>  
Let's remove the tag <xs:schema …..></xs:schema>. Now checking in SQL Server to open XML file and read from it. For that, we have to add the below code in Query Window and check. And, we put this in Query window of SQL Server. It will show like below.
  1. DECLARE @SET1 NVARCHAR(MAX)  
  2. SET @SET1 = '<NewDataSet> < SampleDataTable Name = "Franklin"  
  3. Address = "Hosur"  
  4. Phone = "46945616" / > < SampleDataTable Name = "SAMRAj Gill"  
  5. Address = "DT-HOSUR"  
  6. Phone = "78971651" / > < /NewDataSet>'  
  7. DECLARE @XMLDocPointer INT  
  8. EXEC sp_xml_preparedocument @XMLDocPointer OUTPUT, @SET1  
  9. BEGIN TRANSACTION  
  10. --INSERT INTO dbo.some_table(ID, Name, [Address], Phone)  
  11. select '1'  
  12. as ID, Name, [Address], Phone  
  13. from  
  14. OPENXML(@XMLDocPointer, '/NewDataSet/SampleDataTable', 1) with(Name NVARCHAR(100), [Address] NVARCHAR(100), Phone NVARCHAR(100))  
  15. EXEC sp_xml_removedocument @XMLDocPointer  
OUTPUT
 
ID    Name        Address                 Phone
1      Franklin    Hosur                    46945616
1      SAMRAj   Gill DT-HOSUR  78971651

Now, we have to generate only the below code from C# Class properties or List of class. Then, pass to SQL Server.
  1. <NewDataSet>  
  2.     <SampleDataTable Name="Franklin" Address="Hosur" Phone="46945616" />  
  3.     <SampleDataTable Name="SAMRAj Gill" Address="DT-HOSUR" Phone="78971651" />   
  4. </NewDataSet>  
In this, <NewDataSet> and <SampleDataTable> tags are fixed. We have to generate only he following.
  1. Name="SAMRAj Gill" Address="DT-HOSUR" Phone="78971651" />  
Where First attributes are property names of class. Attribute values are Class object value.
  1. class Employee {  
  2.     public string Name {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string Address {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public string Phone {  
  11.         get;  
  12.         set;  
  13.     }  
  14. }  
  15. List < Employee > oEmp = new List < Employee > ();  
  16. oEmp.Add(new Employee() {  
  17.     Name = "Franklin", Address = "Hosur", Phone = "46945616"  
  18. });  
  19. oEmp.Add(new Employee() {  
  20.     Name = "SAMRAj Gill", Address = "DT-HOSUR", Phone = "78971651"  
  21. });  
  22. string strXML = EmployeeConvertToXML(oEmp);  
You can create your own common method to achive below.
  1. private static string EmployeeConvertToXML(List < Employee > oEmp) {  
  2.     StringBuilder sb = new StringBuilder();  
  3.     sb.Append("<NewDataSet>");  
  4.     foreach(Employee oe in oEmp) {  
  5.         sb.Append("<SampleDataTable Name=\"" + oe.Name + "\" Address=\"" + oe.Address + "\" Phone=\"" + oe.Phone + "\" />");  
  6.     }  
  7.     sb.Append("</NewDataSet>");  
  8.     return sb.ToString();  
  9. }  
The following will be the stored procedure to save to the Table some_table.
  1. Create proc SaveToSome_table  
  2. @SET1 NVARCHAR(MAX)  
  3. AS  
  4. BEGIN  
  5. DECLARE @XMLDocPointer INT  
  6. EXEC sp_xml_preparedocument @XMLDocPointer OUTPUT, @SET1  
  7. BEGIN TRANSACTION  
  8. INSERT INTO dbo.some_table(ID, Name, [Address], Phone)  
  9. select '1'  
  10. as ID, Name, [Address], Phone  
  11. from  
  12. OPENXML(@XMLDocPointer, '/NewDataSet/SampleDataTable', 1) with(Name NVARCHAR(100), [Address] NVARCHAR(100), Phone NVARCHAR(100))  
  13. EXEC sp_xml_removedocument @XMLDocPointer  
  14. END  
Next Recommended Reading Bulk Insert In SQL Server From C#