XML serialization errors when trying to serialize Entity Framework objects

梦想与她 提交于 2019-12-21 05:08:12

问题


I have entities that I am getting via Entity Framework. I'm using Code-First so they're POCOs. When I try to XML Serialize them using XmlSerializer, I get the following error:

The type System.Data.Entity.DynamicProxies.Song_C59F4614EED1B7373D79AAB4E7263036C9CF6543274A9D62A9D8494FB01F2127 was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.

Anybody got any ideas on how to get around this (short of creating a whole new object)?


回答1:


Just saying POCO doesn't really help (especially in this case since it looks like you're using proxies). Proxies come in handy in a lot of cases but make things like serialization more difficult since the actual object being serialized is not really your object but an instance of a 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




回答2:


Sorry, I know I'm coming at this a bit late (a couple YEARS late), but if you don't need the proxy objects for lazy loading, you can do this:

Configuration.ProxyCreationEnabled = false;

in your Context. Worked like a charm for me. Shiv Kumar actually gives better insight into why, but this at least will get you back to work (again, assuming you don't need the proxies).




回答3:


Another way that works independent of the database configuration is by doing a deep clone of your object(s).

I use Automapper (https://www.nuget.org/packages/AutoMapper/) for this in my code-first EF project. Here is some sample code that exports a list of an 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's '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;
    }


来源:https://stackoverflow.com/questions/4912214/xml-serialization-errors-when-trying-to-serialize-entity-framework-objects

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