I am using a domain model generated from a db with entity framework. How can i serialize/deserialize an object instance of this domain model to/from xml? can i use the .edmx file for this? any code samples? thanks
You could use the XmlSerializer class. There is also the DataContractSerializer which was introduced with WCF. For example if you wanted to serialize an existing object to XML using the XmlSerializer
class:
SomeModel model = ...
var serializer = new XmlSerializer(typeof(SomeModel));
using (var writer = XmlWriter.Create("foo.xml"))
{
serializer.Serialize(writer, model);
}
and to deserialize back a XML to an existing model:
var serializer = new XmlSerializer(typeof(SomeModel));
using (var reader = XmlReader.Create("foo.xml"))
{
var model = (SomeModel)serializer.Deserialize(reader);
}
I use this VB Code to serialize my EF model to Xml :
Try
Dim serializer = New XmlSerializer(GetType(GestionEDLService.Biens))
Dim localFolder As StorageFolder = ApplicationData.Current.LocalFolder
Dim sampleFile As StorageFile = Await localFolder.CreateFileAsync("dataFile.xml", CreationCollisionOption.OpenIfExists)
Dim stream As Stream = Await sampleFile.OpenStreamForWriteAsync()
serializer.Serialize(stream, MyEFModel.MyEntity)
Catch ex As Exception
Debug.WriteLine(ex.ToString)
End Try
EDIT: You can also use a DataContractSerializer like this
Imports System.Runtime.Serialization
Public Sub WriteToStream(sw As System.IO.Stream)
Dim dataContractSerializer As New DataContractSerializer(GetType(MyDataSource))
dataContractSerializer.WriteObject(sw, _MyDataSource)
End Sub
Public Sub ReadFromStream(sr As System.IO.Stream)
Dim dataContractSerializer As New DataContractSerializer(GetType(MyDataSource))
_MyDataSource = dataContractSerializer.ReadObject(sr)
End Sub
HTH
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With