Click here to Skip to main content
15,893,337 members
Articles / Programming Languages / C#
Tip/Trick

How to serialize list of linq entities (ex. from DBML)

Rate me:
Please Sign up or sign in to vote.
4.75/5 (3 votes)
10 Dec 2009CPOL 20.1K   7   1
Today I was trying to save list of entities those were generated by DBMLThis code shows how you can store your list in XML string and put it in ViewState, after that you get your list back.Using the CodeYou can use this code as you need.Here is class Serializatorpublic class...
Today I was trying to save list of entities those were generated by DBML

This code shows how you can store your list in XML string and put it in ViewState, after that you get your list back.

Using the Code


You can use this code as you need.

Here is class Serializator
C#
public class Serializator
{
    public static string SerializeLinqList<T>(List<T> list)
    {
        DataContractSerializer dcs = new DataContractSerializer(typeof(List<T>));
        StringBuilder sb = new StringBuilder();
        using (XmlWriter writer = XmlWriter.Create(sb))
        {
            dcs.WriteObject(writer, list);
        }
        return sb.ToString();
    }

    public static List<T> DeserializeLinqList<T>(string xml)
    {
        List<T> list;

        DataContractSerializer dcs = new DataContractSerializer(typeof(List<T>));

        using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
        {
            list = dcs.ReadObject(reader) as List<T>;
        }
        if (list == null) list = new List<T>();
        return list;
    }
}

Here is how it works
C#
public List<sp_LoadCustomDataResult> Items
    {
        get
        {
            
            if(ViewState["Items"] == null)
                return new List<sp_LoadCustomDataResult>();            
            string xml = (string)ViewState["Items"];
            return Serializator.DeserializeLinqList<sp_LoadCustomDataResult>(xml);
        }
        set
        {
            ViewState["Items"] = Serializator.SerializeLinqList<sp_LoadCustomDataResult>(value);
        }
    }

Thank you for your attention. Sorry for my poor english.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Ukraine Ukraine
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionReferences Pin
emorales28-Jun-14 9:00
emorales28-Jun-14 9:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.