Question

I am having an issue regarding the deserialization of an XML class. I need to use a proxy for an IList because XML does not serialize/deserialize on Interfaces. I need to use this proxy because NHibernate does not accept Lists and only accepts interfaces. My issue is only when deserializing. Serialization works fine.

public class EmailCategory
    {
        [XmlAttribute("Id")]
        public virtual long Id { get; set; }
        [XmlAttribute("Name")]
        public virtual string Name { get; set; }
        protected internal virtual IList<EmailBranch> EmailBranches { get; set; }

        [XmlArray("EmailBranches")]
        [XmlArrayItem("EmailBranch", typeof(EmailBranch)]
        public List<EmailBranch> EmailBranchesProxy {
            get { return EmailBranches != null ? EmailBranches .ToList() : null; }
            set { EmailBranches = value; }
        }
    }
Was it helpful?

Solution

A DTO object is probably the cleanest. There's a whole range of issues that could crop up when you try to serialize database objects. However, if you still intend to serialize the object, here's a possible solution:

public class EmailCategory { [XmlAttribute("Id")] public virtual long Id { get; set; } [XmlAttribute("Name")] public virtual string Name { get; set; } protected internal virtual IList EmailBranches { get; set; } //private List _test = new List();

//[XmlArray("EmailBranches")]
//[XmlArrayItem("EmailBranch", typeof(EmailBranch))]
//public virtual List<EmailBranch> EmailBranchesProxy {
//    get { return EmailBranches != null ? EmailBranches.ToList() : null; }
//    set { EmailBranches = value; }
//}

[XmlArray("EmailBranches")]
[XmlArrayItem("EmailBranch", typeof(EmailBranch))]
public virtual List<EmailBranch> EmailBranchesProxy
{
    get 
    {
        var proxy = EmailBranches as List<EmailBranch>;
        if (proxy == null && EmailBranches != null)
        {
            proxy = EmailBranches.ToList();
        }

        return proxy;
    }
    set { EmailBranches = value; }
}

public EmailCategory()
{
    EmailBranches = new List<EmailBranch>();
}

}

The problem you're having is in this line: get { return EmailBranches != null ? EmailBranches .ToList() : null; }. The deserialization process uses the get method and then adds items to the collection. Since you're returning null or a new List object, this does not represent the original EmailBranches collection, hence the serializer correctly deserializes a new EmailBranch object, but addes it to the wrong collection.

The fix, as above, is to initialize the EmailBranches collection inside the constructor (hence it won't be null ... which is probably a good idea anyway) and then type checking in the proxy property appropriately.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top