【问题标题】:XML serialization errors when trying to serialize Entity Framework objects尝试序列化实体框架对象时出现 XML 序列化错误
【发布时间】:2011-02-06 07:43:43
【问题描述】:

我有通过实体框架获得的实体。我正在使用 Code-First,所以它们是 POCO。当我尝试使用 XmlSerializer 对它们进行 XML 序列化时,出现以下错误:

类型 System.Data.Entity.DynamicProxies.Song_C59F4614EED1B7373D79AAB4E7263036C9CF6543274A9D62A9D8494FB01F2127 没想到。使用 XmlInclude 或 SoapInclude 属性来指定 静态未知的类型。

有人对如何解决这个问题有任何想法(除了创建一个全新的对象)吗?

【问题讨论】:

    标签: entity-framework xml-serialization


    【解决方案1】:

    只是说 POCO 并没有真正的帮助(特别是在这种情况下,因为它看起来像您正在使用代理)。代理在很多情况下都会派上用场,但会使序列化等事情变得更加困难,因为被序列化的实际对象并不是真正的对象,而是代理的实例。

    这篇博文应该会给你答案。 http://blogs.msdn.com/b/adonet/archive/2010/01/05/poco-proxies-part-2-serializing-poco-proxies.aspx

    【讨论】:

      【解决方案2】:

      抱歉,我知道我来晚了(晚了几年),但如果你不需要代理对象来延迟加载,你可以这样做:

      Configuration.ProxyCreationEnabled = false;
      

      在您的上下文中。对我来说就像一个魅力。 Shiv Kumar 实际上可以更好地了解原因,但这至少可以让您重新开始工作(再次假设您不需要代理)。

      【讨论】:

        【解决方案3】:

        另一种独立于数据库配置的方法是对对象进行深度克隆。

        我在代码优先的 EF 项目中为此使用 Automapper (https://www.nuget.org/packages/AutoMapper/)。下面是一些导出名为“IonPair”的 EF 对象列表的示例代码:

                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;
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-07-12
          • 2020-07-19
          • 2011-09-26
          • 1970-01-01
          • 2013-05-13
          • 2015-06-01
          • 2011-12-20
          • 1970-01-01
          相关资源
          最近更新 更多