2011-02-06 2 views
4

Entity Framework를 통해 가져 오는 엔티티가 있습니다. 나는 Code-First를 사용하여 POCO입니다. 이 문제를 해결하는 방법에 대한 아이디어 (완전히 새로운 개체를 만드는 짧은)를 가지고Entity Framework 개체를 serialize 할 때 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.

누구 : 나는 XML로 할 때 XmlSerializer가, 나는 다음과 같은 오류가 사용하여 직렬화?

답변

6

그냥 POCO가 도움이되지 않는다는 것을 말하자. (특히 프록시를 사용하는 것처럼 보이기 때문에). 프록시는 많은 경우에 유용하지만 직렬화되는 실제 객체가 실제로 객체가 아니라 프록시의 인스턴스이기 때문에 직렬화와 같은 작업을 더 어렵게 만듭니다.

이 블로그 게시물을 통해 답변을 얻을 수 있습니다. 죄송합니다 http://blogs.msdn.com/b/adonet/archive/2010/01/05/poco-proxies-part-2-serializing-poco-proxies.aspx

5

, 나는이 조금 늦게 (후반 몇 년)에 간다 알고,하지만 당신은 게으른 로딩에 대한 프록시 객체가 필요하지 않은 경우, 당신이 할 수 있습니다 :

Configuration.ProxyCreationEnabled = false; 
을 Context에

나를 위해 매력처럼 일했습니다. Shiv 쿠마 (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; 
    } 
관련 문제