While coding a very simple orchestration in BizTalk Server 2010, I ran into the dreaded "cannot implicitly convert type 'System.Xml.XmlDocument' to '<message type>'" issue. I've seen this happen a few times over the years, and it has often mystified me.
My orchestration defines a message using a schema type. In a Message Assignment shape, I create the message as an XML Document and then assign the document to the message. I initially wrote the code to populate the XML Document with some dummy XML. At that stage, the orchestration compiled OK. Then I changed the code to populate the XML Document with the correct XML and...bang. I could no longer cast the XML Document to the message type.
I spent some time checking this through. I reverted back to the original code (with the dummy content), but the problem persisted. I restarted Visual Studio (several times), deleted the existing ‘bin’ and ‘obj’ folders and re-built, and tried anything else I could think of. No change.
It then occurred to me to think a little more carefully about exactly what I was doing at the point the code broke. My response message is very simple, and to create the XML content, I am therefore concatenating strings. To ensure I got the right XML, I used BizTalk to generate an example of the XML from the schema. The schema contains two root elements for the request and response messages. To generate the XML, I temporarily changed the 'Root Reference' property of the schema from 'default' to the element that represents the response message...
...and forgot to change the property back :-(
So, I changed the property back to 'default' and...
I experimented further and ascertained that if the 'Root Reference' property is set to anything other than 'default', the assignment code in my orchestration breaks. This is totally repeatable on the machine I am using. I spent some time looking at the code that BizTalk generates for schemas. When 'Root Reference' is set to 'default', BizTalk generates separate schema classes for each candidate root element, as well as a class for all root nodes. When set to a specific element, BizTalk outputs a single class, only. Apart from that, I couldn't see anything suspicious.
I can't find anything on the Internet about this, so would be interested if anyone else sees identical behaviour. The lesson, here, of course, is to avoid using schemas with multiple root elements. I have now refactored my schema into two new schemas.