将Entity Framework对象实例持久化到xml

时间:2011-03-13 01:51:36

标签: c# entity-framework asp.net-mvc-2

我正在使用从带有实体框架的数据库生成的域模型。如何将此域模型的对象实例序列化/反序列化为xml?我可以使用.edmx文件吗?任何代码样本? 感谢

2 个答案:

答案 0 :(得分: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 :(得分: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