R – XmlSerializer can’t find EntityObject even though its referenced

entity-frameworkxml-serialization

I hope that someone can help me with this problem that I've been having with XmlSerializer.

I've already looked through this thread: http://social.msdn.microsoft.com/Forums/en-US/asmxandxml/thread/551cee76-fd80-48f8-ac6b-5c22c234fecf/

The error I am getting is:

System.InvalidOperationException: Unable to generate a temporary class (result=1).
error CS0012: The type 'System.Data.Objects.DataClasses.EntityObject' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

I've made sure that my unit test has a reference to System.Data.Entity, so it is able to compile at least. I've also in the app.config made an assembly binding to System.Data.Entity.

Here's my rough class structure

[Serializable] 
[XmlRoot(Namespace = XmlSupport.MyNamespace, ElementName = XmlSupport.WantToSerialize)] 
[XmlInclude(typeof(WantToSerializeBaseClass)]
[XmlInclude(typeof(EntityObject)]
[XmlInclude(typeof(MyEntityObjectSubClass)]
public class WantToSerialize : WantToSerializeBaseClass, IXmlSerializable  (I've tried putting this on the baseclass and the current class)
{
  // methods and classes 
  // I've included XmlIncludes for all the classes that this class has a reference too
  //  even though in the WriteXml it just uses .NET base classes
}

The WantToSerializeBaseClass makes use of some generics, but I've decorated it with XmlIncludes for (EntityObject, and any other classes it makes reference to as well).

the calling code:

var serializerWrite = new XmlSerializer(typeof (WantToSerialize), XmlSupport.ITNNamespace); 

fails

However if I do:

var serializerWrite = new XmlSerializer(typeof (WantToSerialize), new Type[] {typeof(EntityObject)}); 

it is succesfull.

Any thoughts would be most helpful.

UPDATED
I've tracked the problem down to a method in the WantToSerializeBaseClass

public abstract void ConvertFromEntity<TtoCopy>(TtoCopy toCopy) where TtoCopy : MyEntityObjectSubClass;

Where MyEntityObjectSubClass is a subclass of EntityObject, that adds a few methods that I want on my entity objects. The MyEntityObjectSubClass looks like this:

[Serializable]
[XmlInclude(typeof(EntityObject))]
public abstract class MyEntityObjectSubClass : EntityObject, IMyEntityObjectSubClass 

Again any thoughts would be great

Best Answer

If you don't have any code that requires a reference at compile time then that reference won't be included in the built assembly. You can use a tool like Reflector to check whether the reference is making it into your assembly.

One thing you can try is adding a static method to WantToSerialize that creates the XmlSerializer. The assembly containing WantToSerialize must already have a good reference to EntityObject, so this should solve the problem.

Related Topic