August 24, 2014

System.InvalidOperationException: There was an error generating the XML document.



System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: The type System.Data.Entity.DynamicProxies.Table2_UNIQUE_ID was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write2_Network(String n, String ns, Network o, Boolean isNullable, Boolean needType)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write5_ArrayOfNetwork(Object o)
   at Microsoft.Xml.Serialization.GeneratedAssembly.ListOfNetworkSerializer.Serialize(Object objectToSerialize, XmlSerializationWriter writer)
   at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
   --- End of inner exception stack trace ---
   at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
   at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o, XmlSerializerNamespaces namespaces)
   at System.Web.Services.Protocols.XmlReturnWriter.Write(HttpResponse response, Stream outputStream, Object returnValue)
   at System.Web.Services.Protocols.HttpServerProtocol.WriteReturns(Object[] returnValues, Stream outputStream)
   at System.Web.Services.Protocols.WebServiceHandler.WriteReturns(Object[] returnValues)
   at System.Web.Services.Protocols.WebServiceHandler.Invoke()

To overcome from this errors please add the following line to the constructor of the DataContext. Then everything will work fine again.


this.Configuration.ProxyCreationEnabled = false;

August 18, 2014

Cannot serialize interface System.Collections.Generic.IEnumerable Error



public Table1()
        {
            this.Table2s = new HashSet<Table2>();
        }   

        public virtual ICollection<Table2> Table2s { get; set; }

When I try to get all the data from Table1 by using LINQ, I got this following Issue when trying to run my web service.

Cannot serialize interface System.Collections.Generic.IEnumerable`1[[TestApp1.Table1, TestApp1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].

After spending lot of time on this, finally figured out the solution from stackoverflow link: http://stackoverflow.com/questions/3630052/xml-serialization-problem-in-c-sharp-asp-net

All public properties defined in the code are visible to the xml serializer, and it will always serialize them.

We have to make sure to put [XmlIgnore] attributes on the properties that should NOT be serialized. So the final code looks like this:

public Table1()
        {
            this.Table2s = new HashSet<Table2>();
        }   

[XmlIgnore]

        public virtual ICollection<Table2> Table2s { get; set; }