我正在尝试将实现 DbContext 的对象写入文件,但是我无法让 DataContractSerializer 工作。我正在查看有关该主题的帖子http://www.riggshill.com/home/node/24但我收到了一个错误:
Error 10 'System.Runtime.Serialization.DataContractSerializer' does not contain a definition for 'Serialize' and no extension method 'Serialize' accepting a first argument of type 'System.Runtime.Serialization.DataContractSerializer' could be found (are you missing a using directive or an assembly reference?)
我的班级如下所示:
public class ManagementDbContext : DbContext
{
public DbSet<RemoteHost> RemoteHosts {get;set;}
public DbSet<DataSource> DataSources { get; set; }
public override int SaveChanges()
{
using (FileStream fs = File.OpenWrite("ManagementData.xml"))
{
XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(fs, Encoding.UTF8);
DataContractSerializer srlz = new DataContractSerializer(typeof(ManagementDbContext));
srlz.Serialize(writer, this);
writer.Close(); // ensure it's properly flushed
}
return base.SaveChanges();
}
}
编辑:
好的,事实证明我遵循的示例代码很糟糕,而且我有错误。该行srlz.Serialize(writer,this)
应该srlz.WriteObject(writer,this)
如此处所示DataContractSerializer
此外,我无法序列化 DbContext 的实现,并且缺少类上的 [Serializable] 和 [DataContract] 属性,以及 Daniil 指出的成员上的 [DataMember()]。