Tuesday, February 16, 2010

XSD to NHibernate-WCF contract converter

Guess you want to generate a WCF Data Contract from an XSD. In this case you use svcutil with /dconly option. This tool is based on
XsdDataContractImporter, so it can convert XSD files the same way, as svcutil does it.

But what do you do if you want to persist your object with NHibernate? You cannot do this with the contract generated from svcutil. The core of the problem is, that though you can switch the collection type with the /ct: options to IList. the generated data contract will not build. Second issue is that all the properties are generated public but not virtual public as we need this for NHibernate.

As svcutil is basically a wrapper around framework classes, I slapped together a small custom XSD to Class converter that generates classes that can be directly filled with NHibernate. All the customization is encapsulated in xsdconverter.cs. So feel free to change the frontend (WPF here) to whatever you like.

90% of the code is dedicated to another feature of the generator. It is capable of generating code comments from your <xs:annotations> elements. This code is based on the code released by Xsd2Code project.

You can get it here.

Due to some unlucky limitations of System.Runtime.Serialization (see comments) using the NHibernate option the serialized object may not be valid against the schema. As long as you do not require valid XML against your schema (and you probably won't) this restriction does not matter though.

No comments: