Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

persist Entity Framework object instance to xml

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

like image 461
user603007 Avatar asked Mar 13 '11 01:03

user603007


2 Answers

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);
}
like image 85
Darin Dimitrov Avatar answered Sep 28 '22 10:09

Darin Dimitrov


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

like image 43
Cédric Bellec Avatar answered Sep 28 '22 10:09

Cédric Bellec