XML serialization errors when trying to serialize

2019-03-29 10:16发布

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)?

3条回答
2楼-- · 2019-03-29 10:48

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;
    }
查看更多
对你真心纯属浪费
3楼-- · 2019-03-29 10:53

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).

查看更多
走好不送
4楼-- · 2019-03-29 10:55

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

查看更多
登录 后发表回答