2

I have a problem that I'm working in nHibernate project that have the following object:

[Serializable]
public class Prototype
{
    public virtual long Id { get; private set; }
    public virtual string Name { get; set; }   
    public virtual IList<AttributeGroup> AttributeGroups { get; private set; }
}

I have created a method to deserialize an XML file and put it into object of type Prototype as following :

public static T Deserialize(string fileName)
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    XmlTextReader xmlTextReader = new XmlTextReader(fileName);
    Object c = xmlSerializer.Deserialize(xmlTextReader);
    return (T)c;
}

The problem now is that I have the following exception:

Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericBag`1[BCatalog.Entities.AttributeGroup]' to type 'System.Collections.Generic.List`1[BCatalog.Entities.AttributeGroup]'.

I can't change the type of the IList because of the nHibernate and I want to deserialize the object.

What should I do to solve this problem ?

forsvarir
  • 10,749
  • 6
  • 46
  • 77
Amira Elsayed Ismail
  • 9,216
  • 30
  • 92
  • 175
  • How is it trying to cast to a List`1? This does not appear anywhere in these examples. Could you add the contents of the serialized XML? Maybe that helps. – Pieter van Ginkel Oct 18 '10 at 16:23
  • 2
    possible duplicate of [NHibernate: How do I XmlSerialize an ISet?](http://stackoverflow.com/questions/1958684/nhibernate-how-do-i-xmlserialize-an-isett) – Mauricio Scheffer Oct 18 '10 at 20:25

1 Answers1

0

Interfaces seems to be cumbersome for serialization/deserialization processes. You might need to add another public member to the class that uses a concrete type and mark the interface property as xml ignore. This way you can deserialize the object without loosing your contract base.

Something like the following:

[Serializable]
public class Prototype
{
    public virtual long Id { get; private set; }
    public virtual string Name { get; set; }   
    [XMLIgnore]
    public virtual IList<AttributeGroup> AttributeGroups { 
        get { return this.AttributeGroupsList; } 
    }
    public virtual List<AttributeGroup> AttributeGroupsList { get; private set;}
}

For more information about deserialization attributes please check XmlAttributes Properties.

Regards,

wacdany
  • 991
  • 1
  • 10
  • 19