Search code examples
wcfserializationodata

Rename a property in OData DataServiceContext


Is it possible to rename a property that will be serialized for a WCF OData System.Data.Services.Client?

I have a class that's called Mailbox and a property that is also called Mailbox. This is not possible in C# because in this case the name Mailbox is reserved for the constructor.

Generating code with DataSvcUtil.exe for the csdl gives: error 0042: Name Mailbox cannot be used in type Mailbox. Member names cannot be the same as their enclosing type.

So I want to rename the property for serialization. I tried serveral attributes, but none of them worked.

[global::System.Data.Services.Common.DataServiceKeyAttribute("ID")]
public partial class Mailbox
{
   [DataMember(Name = "Mailbox")]
   [XmlElement(ElementName = "Mailbox")]
   [JsonProperty(PropertyName = "Mailbox")]       
   [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
   public string MailBox
   {
     get
     {
       return this._mailbox;
     }
     set
     {
       this.OnsMailboxChanging(value);
       this._mailbox = value;
       this.OnsMailboxChanged() 
     }
   }
   private string _mailbox;
}

Solution

  • I found a workaround by moving the code to Visual Basic, since it is allowed in VB to have a property and a class with the same name. I dont like this solution, but at least I can continue coding.