5

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

2 Answers 2

6

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.