2011-02-06 83 views
4

我有通過實體框架獲取的實體。我使用Code-First,因此他們是POCO。當我嘗試XML序列化使用它們XmlSerializer的,我得到以下錯誤:嘗試序列化實體框架對象時出現XML序列化錯誤

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.

任何人有關於如何解決這個問題的任何想法(短創造了一個全新的對象)?

回答

5

對不起,我知道我在這個有點晚(幾年下旬)來​​了,但如果你沒有需要延遲加載代理對象,你可以這樣做:

Configuration.ProxyCreationEnabled = false; 

在您的上下文中。爲我工作就像一個魅力。 Shiv Kumar實際上更深入地瞭解了爲什麼,但這至少會讓你重新工作(再次假設你不需要代理人)。

0

獨立於數據庫配置工作的另一種方法是對對象進行深層克隆。

我在我的代碼優先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; 
    }