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.