Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericBag to type 'System.Collections.Generic.List

StackOverflow https://stackoverflow.com/questions/16642466

문제

I am trying to load the domain class by deserializing an xml file. So I have used System.Collections.Generic.List in the domain class. But when I try to save the object using Session object then it is failing with exception "Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericBag1[MyFirstMapTest.Class5]' to type 'System.Collections.Generic.List1[MyFirstMapTest.Class5]'." This issue was posted in some of the previous discussion and the answer was to use use IList instead of List(Unable to cast object of type NHibernate.Collection.Generic.PersistentGenericBag to List)

But, If I use IList then I am unable to Deserialize the xml in to Domain class.

XmlTextReader xtr = new XmlTextReader(@"C:\Temp\SampleInput.xml");
XmlSerializer serializer = new XmlSerializer(objClass5.GetType());
objClass5 = (MyFirstMapTest.Class5)serializer.Deserialize(xtr);
session.Save(objClass5);

It is throwing the below error "Cannot serialize member xxxxx of type System.Collections.Generic.IList`1[[xxxxxxxxxx, Examples, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] because it is an interface."

I have tried to use PersistentGenericBag instead of List but PersistentGenericBag is not serializable. So Deserialization is not working.

How can I resolve this issue? Thank you for looking at this issue.

도움이 되었습니까?

해결책 2

You can create two properties like this in your class:

public class Sample
{
    private IList<Sample> _list;

    [XmlIgnoreAttribute]
    public virtual IList<Sample> List
    {
        get
        {
            return _list;
        }
        set
        {
            _list = value;
        }
    }

    public virtual List<Sample> List
    {
        get
        {
            return (List<Sample>)_list;
        }
        set
        {
            _list = value;
        }
    }
}

And you only map your IList Property.

다른 팁

You may try to use backing field for NHibernte binding and property for Serialization, where property will be of type List, while backing field - IList.

Edit
fluent mapping may look like this:

public class HierarchyLevelMap : IAutoMappingOverride<HierarchyLevel>
{
    public void Override(AutoMapping<HierarchyLevel> mapping)
    {
        mapping.HasMany(x => x.StructuralUnits)
            .Access.ReadOnlyPropertyThroughCamelCaseField();
    }
}

entity:

public class HierarchyLevel : IEntity
{
    private readonly IList<StructuralUnit> structuralUnits = new List<StructuralUnit>();

    public virtual List<StructuralUnit> StructuralUnits
    {
        get { return structuralUnits; }
        set { structuralUnits = value; }
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top