Migrate an instance of an Entity Framework object in xml

I am using a domain model generated from db with an entity infrastructure. 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? thank

+5
source share
2 answers

You can use the XmlSerializer class . There is also a DataContractSerializer that was introduced with WCF. For example, if you want to serialize an existing object in XML using a class XmlSerializer:

SomeModel model = ...
var serializer = new XmlSerializer(typeof(SomeModel));
using (var writer = XmlWriter.Create("foo.xml"))
{
    serializer.Serialize(writer, model);
}

and deserialize the XML back into the existing model:

var serializer = new XmlSerializer(typeof(SomeModel));
using (var reader = XmlReader.Create("foo.xml"))
{
    var model = (SomeModel)serializer.Deserialize(reader);
}
+5
source

VB EF 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: DataContractSerializer,

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

+1

All Articles