How to serialize and save an object to database as Xml using Linq to SQL

你说的曾经没有我的故事 提交于 2019-12-22 05:28:08

问题


I were using FileStream to Serialize an Object to Xml and Save to the disk

Stream str = new FileStream(@"serializedstate.xml", FileMode.OpenOrCreate)
XmlSerializer x = new XmlSerializer(typeof(GridState));
x.Serialize(str, new GridState
        {
            GridName= txtGridName.Text,
            GridColumns = GetGridColumnStates()
        });

This works fine and Xml file is generated on disk. How do I save serialized Object as Xml into a Sql Server 2008 database's XML column using Linq to SQL? And how to deserialize the same from database?


回答1:


To serialize into an XElement

        XmlSerializer x = new XmlSerializer(typeof(GridState));
        XDocument doc = new XDocument();

        using (XmlWriter xw = doc.CreateWriter())
        {
            x.Serialize(xw, new GridState
                {
                    GridName= txtGridName.Text,
                    GridColumns = GetGridColumnStates()
                });
            xw.Close();
        }

        XElement el = doc.Root;

To deserialize

        using (XmlReader xr = el.CreateReader())
        {
            GridState myDeserializedObject = x.Deserialize(xr) as GridState;
            xr.Close();
        }



回答2:


In sql you must have colum type XML and in linq the type of Colum must be XElement than you can manipulate throw Linq.



来源:https://stackoverflow.com/questions/1825124/how-to-serialize-and-save-an-object-to-database-as-xml-using-linq-to-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!