我正在尝试将实现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()]。
答案 0 :(得分:1)
首先 - 您需要在ManagementDbContext中使用Serializable和DataContract属性。第二,您无法序列化您的对象,因为DbContext未标记任何属性。
的基本要约