XML serialization errors when trying to serialize Entity Framework objects

I have objects that I get through the Entity Framework. I use Code-First, so they are POCOs. When I try to serialize XML using XmlSerializer, I get the following error:

Type System.Data.Entity.DynamicProxies.Song_C59F4614EED1B7373D79AAB4E7263036C9CF6543274A9D62A9D8494FB01F2127 was not expected. Use XmlInclude or SoapInclude to indicate types that are not known statically.

Anyone have any ideas on how to get around this (without creating a whole new object)?

+4
source share
3 answers

They just say that POCO really does not help (especially in this case, since it looks like you are using a proxy). Proxies come in handy in many cases, but make things like serialization more complicated, because the actual object that is being serialized is not really your object, but an instance of the proxy.

This blog post should give you your answer. http://blogs.msdn.com/b/adonet/archive/2010/01/05/poco-proxies-part-2-serializing-poco-proxies.aspx

+6
source

Sorry, I know I'm a little late (a couple of years late), but if you don't need proxies for lazy loading, you can do this:

Configuration.ProxyCreationEnabled = false; 

in your context. Worked for me like a charm. Shiv Kumar actually gives a better idea of ​​why, but that will at least get you back to work (again, assuming you don't need proxies).

+5
source

Another way that works regardless of the database configuration is to make a deep clone of your object (s).

I am using Automapper ( https://www.nuget.org/packages/AutoMapper/ ) for this in my first EF project. Here is an example of code that exports a list of EF objects called "IonPair":

  public bool ExportIonPairs(List<IonPair> ionPairList, string filePath) { Mapper.CreateMap<IonPair, IonPair>(); //creates the mapping var clonedList = Mapper.Map<List<IonPair>>(ionPairList); // deep-clones the list. EF 'DynamicProxies' are automatically ignored. var ionPairCollection = new IonPairCollection { IonPairs = clonedList }; var serializer = new XmlSerializer(typeof(IonPairCollection)); try { using (var writer = new StreamWriter(filePath)) { serializer.Serialize(writer, ionPairCollection); } } catch (Exception exception) { string message = string.Format( "Trying to export to the file '{0}' but there was an error. Details: {1}", filePath, exception.Message); throw new IOException(message, exception); } return true; } 
0
source

Source: https://habr.com/ru/post/1338613/


All Articles