How to use XMLSerializer with a Castle ActiveRecor

2019-04-10 01:49发布

问题:

I am trying to use the XMLSerializer with a castle active record class which looks like the following:

[ActiveRecord("Model")]
public class DataModel : ActiveRecordBase
{
    private IList<Document> documents;

    [XmlArray("Documents")]
    public virtual IList<Document> Documents
    {
        get { return documents; }
        set
        {
            documents = value;    
        }
    }
}

However, the XMLSerializer runs into trouble because of the IList interface. (Raises exception: Cannot serialize member 'DataModel.Documents' of type 'System.Collections.Generic.IList`1....)

I read elsewhere that this is a limitation in the XMLSerializer and the recommended workaround is to declare it as a List<T> interface instead.

Therefore I tried changing the IList<Document> to List<Document>. This causes ActiveRecord to raise an Exception: Type of property DataModel.Documents must be an interface (IList, ISet, IDictionary or their generic counter parts). You cannot use ArrayList or List as the property type.

So, the question is: How do you use the XMLSerializer with a Castle ActiveRecord containing an IList member?

回答1:

Interesting... the best I can suggest is to use [XmlIgnore] on Documents - and does ActiveRecord have a similar way of ignoring a member? You could do something like:

[XmlIgnore]
public virtual IList<Document> Documents
{
    get { return documents; }
    set
    {
        documents = value;    
    }
}

[Tell ActiveRecord to ignore this one...]
[XmlArray("Documents"), XmlArrayItem("Document")]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public Document[] DocumentsSerialization {
    get {
         if(Documents==null) return null;
         return Documents.ToArray(); // LINQ; or do the long way
    }
    set {
         if(value == null) { Documents = null;}
         else { Documents = new List<Document>(value); }
    }
}


回答2:

Microsoft won't implement this, so you have to work around it. One way would be to use the non-generic IList:

[ActiveRecord("Model")]
public class DataModel : ActiveRecordBase<DataModel> {
    [XmlArray("Documents")]
    [HasMany(typeof(Document)]
    public virtual IList Documents {get;set;}
}

Here's some more information about this bug.