0

我正在尝试将实现 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()]。

4

1 回答 1

1

首先 - 您需要在 ManagementDbContext 中使用SerializableDataContract属性。其次,您无法序列化您的对象,因为DbContext未标记任何属性。

序列化基础知识

于 2013-03-25T10:55:47.730 回答