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; }
}
}
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();
}
The problem you’re having is in this line:
get { return EmailBranches != null ? EmailBranches .ToList() : null; }. The deserialization process uses thegetmethod and then adds items to the collection. Since you’re returning null or a new List object, this does not represent the originalEmailBranchescollection, hence the serializer correctly deserializes a newEmailBranchobject, but addes it to the wrong collection.The fix, as above, is to initialize the
EmailBranchescollection 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.