Friday, October 18, 2013

Extend WCF automatically generated DTO with partial classes

Suppose that you have some WCF service which has web method which returns instance of Foo class (this class should be marked with [DataContract] attribute and its members with [DataMember] attribute as you probably know) and VS generated proxy for this web service. VS also will generate all dependent classes necessary for successful compilation of the proxy, including mentioned Foo class. Now you need to extend it with partial class (there may be a lot of reasons), how to do it?

The answer depends on actual configuration of the service and client, but there is one thing which you should keep in mind. Let's assume that we have the following automatically generated Foo class on the client side:

   1: [Serializable]
   2: public class Foo
   3: {
   4:     [XmlElement]
   5:     public string Title { get; set; }
   6: }

We want to add additional property which will be used only on client side, so we create partial class for it like this:

   1: public partial class Foo
   2: {
   3:     public string Status { get; set; }
   4: }

With this approach we may get the following exception:

There was an error reflecting 'Foo'.
at System.Xml.Serialization.XmlReflectionImporter.ImportMembersMapping(XmlReflectionMember[] xmlReflectionMembers, String ns, Boolean hasWrapperElement, Boolean rpc, Boolean openModel, RecursionLimiter limiter)

In order to avoid it, add [XmlIgnore] attribute for your property:

   1: public partial class Foo
   2: {
   3:     [XmlIgnore]
   4:     public string Status { get; set; }
   5: }

You may also try to change auto property from example above to classic property with private field and add [NonSerializable] attribute to the field, but in this case added property won’t be serialized on the client side, which in turn may cause another problems.

Hope that this information will help someone.

No comments:

Post a Comment