使用子项c#序列化对象

Jak*_*kob 8 c# serialization

var store = GetStore(); using(IsolatedStorageFileStream fileStream = store.OpenFile(RootData,FileMode.Create)){DataContractSerializer serializer = new DataContractSerializer(typeof(List)); serializer.WriteObject(fileStream,rootdatalist); }

但这只是序列化了rootdatalist,而不是子项.rootdatalist有一个节点List属性,我该如何序列化它,以便我得到列表层次结构序列化?

由于它是dbml生成的对象,因此Root的Nodes属性是

public System.Data.Linq.Table<Node> Nodes
{
    get
    {
        return this.GetTable<Node>();
    }
}
Run Code Online (Sandbox Code Playgroud)

我的Datacontext返回是:

public List<Root> GetRootList(Guid userid)
{
   DataLoadOptions loadopts = new DataLoadOptions();
   loadopts.LoadWith<Root>(s => s.Nodes);
   this.DataContext.LoadOptions = loadopts;
   return this.DataContext.Root.Where(s => s.Nodes.Count(n => n.UserId == userid) > 0).ToList();
}
Run Code Online (Sandbox Code Playgroud)

Node实体集在我的dbml设计器中看起来如下

[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Root_Node", Storage="_Nodes", ThisKey="Id", OtherKey="RootId")]
[global::System.Runtime.Serialization.DataMemberAttribute(Order=5, EmitDefaultValue=false)]
public EntitySet<Node> Nodes
{
    get
    {
        if ((this.serializing && (this._Nodes.HasLoadedOrAssignedValues == false)))
        {
            return null;
        }
        return this._Nodes;
    }
    set
    {
        this._Nodes.Assign(value);
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,我必须[Include]在我的属性上方标记或者不会加载任何内容.编辑::给其他想要序列化dbml类的人http://blogs.msdn.com/b/wriju/archive/2007/11/27/linq-to-sql-enabling-dbml-file-for-wcf.aspx

Mar*_*ell 9

您是否可以包含有关合同类型的更多信息?例如,我希望Root将该成员标记为数据合同,并将该成员作为数据成员,例如:

[DataContract]
public class Root {
    [DataMember]
    public List<SubItem> Nodes {get;private set;}
}

[DataContract]
public class SubItem {
    [DataMember]
    public int Foo {get;set;}

    [DataMember]
    public string Bar {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

这应该工作.如果没有,那么看到你的类型(或者它们的简化版本,这说明了问题)真的很有帮助.


Ode*_*ded 7

DataContractSerializer需要了解所有在你的对象图的类型.

使用构造函数重载,让您指定这些以及根类型:

DataContractSerializer serializer = new DataContractSerializer(typeof(List<Root>), listOfOtherTypes);
Run Code Online (Sandbox Code Playgroud)