In this blog, we will discuss the way to submit the data of a model list to SQL Server to save all records of the list at once. We can do this by converting the model list to XML and then that XML can be submitted to SQL Server through Store Procedure. We can read the XML in SQL Server to use the data for SQL queries. I hope this will be helpful in the situations where we need to save multiple records of same entity or model by looping the list.
Requirement
There might be a situation where you have a model named "Student" and you want to save a list of students. Generally, in Entity Framework, we have to iterate the list using for loop and have to save each record one by one. It takes a lot of time to save a large number of records. Even if we have any stored procedure to save single record and use that to save a list by looping, it takes more time. In this case too, the application has to make a connection call each time.
Advantages of using XML post instead of looping
- Single call to SQL server to save the data
- Performance improvement as there is no need to make multiple calls to SQL
- Adding/Removing any field in XML does not require many changes. If you add any property/field in the model list, there is no need to change input paramter of SQL Stored Procedure.
Example
Suppose, we have a model named "Student".
- public class Student
- {
- public int StudentId { get; set; }
- public int RoleNumber { get; set; }
- public string Name { get; set; }
- }
You can convert your model list into XML like this.
- List<Student> StudentList= new List<Student>();
- StudentList.Add(new Student{StudentId=101,RoleNumber=185,Name="Test1" });
- StudentList.Add(new Student{StudentId=102,RoleNumber=186,Name="Test2" });
- foreach(var a in StudentList)
- {
- Console.WriteLine(a.Name);
- }
- string xml = null;
- using (StringWriter sw = new StringWriter())
- {
- XmlSerializer xs = new XmlSerializer(typeof(List<Student>));
-
- xs.Serialize(sw, StudentList);
-
- try
- {
- xml = sw.ToString();
-
- }
- catch (Exception e)
- {
- throw e;
- }
- }
You will have to pass this XML as a string parameter to SQL Server. Suppose the name of the parameter used to pass XML is @data, here is SQL Stored Procedure to save/update the records passed via XML.
-
- CREATE Procedure SaveStudentData
- (
- @data nvarchar(max)
- )
- AS
- Begin
- DECLARE @xmldata XML=CAST(@data AS XML);
- BEGIN TRANSACTION;
- BEGIN TRY
- Update S set RoleNumber=x.v.value('RoleNumber[1]','int'), Name= x.v.value('Name[1]','varchar(50)')
- from Student S INNER JOIN @xmldata.nodes('ArrayOfStudent/Student') as x(v)
- on CPD.StudentId=x.v.value('StudentId[1]','int')
- END TRY
- BEGIN CATCH
- IF @@TRANCOUNT > 0
- ROLLBACK TRANSACTION;
-
- END CATCH
- IF @@TRANCOUNT > 0
- COMMIT TRANSACTION;
-
- END
-
This way, you can insert/update/delete the bulk data according to the requirement in just one SQL call.