DataContractSerializer with Multi-tiered data structures

瘦欲@ 提交于 2019-12-11 06:59:56

问题


I'm attempting to implement a DataContractSerializer to generate an XML file that represents our somewhat complicated object model. The root object has multiple ICollection properties, one of which has multiple ICollection properties, multiples of which have multiple ICollection properties... you get the idea.

I decorated all my relevant classes with [DataContract(Name = "foo")] tags, read this question about using Include(), and started framing it out. As I put together the top layer, I wondered if the second layer would need explicit declarations as well. Here's what I have so far:

    public void Serialize(string DataCode)
    {
        Product prod = context.Products
            .Include(p => p.Products)
            .Include(p => p.References)
            .Include(p => p.Dates)
            .Include(p => p.Weights)
            .Include(p => p.Notes)
            .Include(p => p.Rules)  // Rules have PriceConditions, which have Prices...
            .Include(p => p.DataBooks)
            .First(m => m.ProductCode == DataCode);
        FileStream fs = new FileStream(path,FileMode.Create);
        XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(fs);
        DataContractSerializer serializer =  new DataContractSerializer(typeof(Product));
        serializer.WriteObject(writer, prod);
    }

So, do I need to do something with Rules in order to ensure that the entire structure gets written, or does Include() know to tunnel deep into the structure and load each element?


回答1:


You would need to explicitly include the lower levels as well.

Product prod = context.Products
    .Include(p => p.Rules.Select(r => r.PriceConditions.Select(p => p.Prices)));
  • Serialize Entity Framework object with children to XML file
  • MSDN page on Include() with examples


来源:https://stackoverflow.com/questions/29902500/datacontractserializer-with-multi-tiered-data-structures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!