locked
Serializing an Entity with Child Entities when saving session state. RRS feed

  • Question

  • I have an Windows Store 8.1 app and I am trying to save the state during a suspend and shutdown.  I found these serialization functions:

            public static string SerializeObject(object obj)
            {
                MemoryStream stream = new MemoryStream();
                System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType(), Common.SuspensionManager.KnownTypes);
                ser.WriteObject(stream, obj);
                byte[] data = new byte[stream.Length];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(data, 0, data.Length);
                return Convert.ToBase64String(data);
            }
    
            public static T DeserializeObject<T>(string input)
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
                MemoryStream stream = new MemoryStream(Convert.FromBase64String(input));
                return (T)ser.ReadObject(stream);
            }
    

    They work well unless the Entity has Child Entities.  I am using Entity Framework and it Generates the Child Entities as DataServiceCollections.  These serialize fine, but when you resume the program and they get deserialized, you get the error:

    An item could not be added to the collection. When items in a DataServiceCollection are tracked by the DataServiceContext, new items cannot be added before items have been loaded into the collection.

    Serialization Function Call is:

    e.PageState["SelectedEstimate"] = StringSerializer.SerializeObject(Est);

    The deserialization call is:

    Est = StringSerializer.DeserializeObject<Estimate>((string)e.PageState["SelectedEstimate"]);

    The Est object is of type Estimate and it has several child collections which are created as type DataServiceCollection.  Is there a way to serialize these such that they can be deserialized without the error?

    Any help would be greatly appreciated.

    Jim


    Jim Wilcox

    Friday, December 6, 2013 3:27 AM

All replies