How to use XMLSerializer with a Castle ActiveRecord containing an IList<T> member

限于喜欢 提交于 2019-12-06 06:18:46

问题


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.



来源:https://stackoverflow.com/questions/753099/how-to-use-xmlserializer-with-a-castle-activerecord-containing-an-ilistt-membe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!