2011-03-13 121 views
5

我正在使用從具有實體框架的數據庫生成的域模型。我如何序列化/反序列化這個領域模型的對象實例到/從XML?我可以使用.edmx文件嗎?任何代碼示例? 謝謝將實體框架對象實例保存到xml

回答

5

您可以使用XmlSerializer類。還有WCF推出的DataContractSerializer。例如,如果你想使用XmlSerializer類的現有對象序列化到XML:

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

和反序列化回XML到現有的模型:

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

我用這個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 

編輯:您還可以使用的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 

HTH