Wednesday, June 8, 2011

Serialization in .Net

Many times we are faced with the situation where we need to save records in different tables and these are inter-linked and having a relationship. Now the problem is how to send these records from application to database and then save them maintaining their relationships intact. Further all this should be fail proof so that if any error is encountered in the whole operation then all is rolled back. In this post I am going to discuss about how to handle this situation by an example. The key points that I am going to touch is Serialization and XML.

For example we have a application where we are registering a student. For this we are saving the basic information of the student, the subjects that he has chosen. Thus the outline of the student registration data would be as follows:



Now the number of records in Subject for a student can be more then one i.e. for a single BasicInfo record of a student there can be multiple Subject records i.e. a one to many relationship. The entity for Student will be as follows:

public class Student
    public int RollNo { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Address { get; set; }
    public int Class { get; set; }
    public bool Gender { get; set; }

    public List<Subjects> ListSubject { get; set; }


public class Subjects
    public Subjects(int subjectId, string subjectName)
        SubjectId = subjectId;
        SubjectName = subjectName;

    public int SubjectId { get; set; }
    public string SubjectName { get; set; }   

Here to maintain the relationships of one to many I have used List collection for subjects. This collection would contain all the subjects that the student chooses. We fill the entity as follows:

Student obj = new Student();
obj.Name = "Jai";
obj.RollNo = 100;
obj.Age = 27;
obj.Class = 10;
obj.Gender = true;
obj.Address = "New Delhi, India";

obj.ListSubject = new List<Subjects>();
obj.ListSubject.Add(new Subjects(1, "English"));
obj.ListSubject.Add(new Subjects(2, "Maths"));
obj.ListSubject.Add(new Subjects(3, "Physics"));
obj.ListSubject.Add(new Subjects(4, "Computers"));

Now to convert this into XML we would serialize the Student object. The code for it is as follows:

StringBuilder builder = new StringBuilder();
System.Xml.Serialization.XmlSerializer x =
new System.Xml.Serialization.XmlSerializer(obj.GetType());

using (StringWriter writer = new StringWriter(builder))
x.Serialize(writer, obj);

string myXml = builder.ToString();

The XML generated for it is as follows:

Thus we have generated the XML of the Student entity class using serialization and we have also maintained the one to many relationship between the StudentInfo and Subjects. In the next post I will discuss how to use this consume this XML in sql server and save the data in the tables.

1 comment:

Comments to this post


Related Posts with Thumbnails