I have a model with some properties:
public class Invoice
{
public string InvoiceNumber { get; set; }
[NotMapped]
public string Title
{
get
{
string title = "";
//some algorithm
return title;
}
}
}
My model has two properties: One of them is read-only (Title) as it's generated programmatically.
I'm generating a XMLDocument from this model (generic approach):
private XmlDocument GenerateXmlDocument()
{
XmlDocument xmlDocument = new XmlDocument();
XmlSerializer xmlSerializer = new XmlSerializer(_objectToSerialize.GetType());
using (MemoryStream xmlStream = new MemoryStream())
{
xmlSerializer.Serialize(xmlStream, _objectToSerialize);
xmlStream.Position = 0;
xmlDocument.Load(xmlStream);
}
//Set namespace
xmlDocument.DocumentElement.SetAttribute("xmlns", XmlNamespace);
return xmlDocument;
}
However it seems my read-only property isn't read by GenerateXmlDocument
. How to solve this issue?
The XMLSerializer will not Serialize readonly properties. This is a limitation. However you should serialize the field "title" anyways. To do that you could use the DataContractSerializer. It is more powerful and allows to serialize the fields you are using within your getter.