无法将'NHibernate.Collection.Generic.PersistentGenericBag类型的对象强制转换为'System.Collections.Generic.List

时间:2013-05-20 04:10:36

标签: nhibernate fluent-nhibernate fluent ilist

我试图通过反序列化xml文件来加载域类。所以我在域类中使用了System.Collections.Generic.List。但是,当我尝试使用Session对象保存对象时,它失败,异常“无法转换类型的对象'NHibernate.Collection.Generic.PersistentGenericBag 1[MyFirstMapTest.Class5]' to type 'System.Collections.Generic.List 1 [MyFirstMapTest.Class5]'。”此问题已在之前的一些讨论中发布,答案是使用IList而不是List(Unable to cast object of type NHibernate.Collection.Generic.PersistentGenericBag to List

但是,如果我使用IList,那么我无法将xml反序列化为Domain类。

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

抛出以下错误 “无法序列化类型System.Collections.Generic.IList`1 [[xxxxxxxxxx,Examples,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]]的成员xxxxx,因为它是一个接口。”

我曾尝试使用PersistentGenericBag而不是List,但PersistentGenericBag不可序列化。所以反序列化不起作用。

如何解决此问题?感谢您查看此问题。

2 个答案:

答案 0 :(得分:1)

您可以尝试使用NHibernte绑定的后备字段和序列化的属性,其中属性类型为List,而后备字段为IList。

修改
流畅的映射可能如下所示:

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

实体:

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

    public virtual List<StructuralUnit> StructuralUnits
    {
        get { return structuralUnits; }
        set { structuralUnits = value; }
    }
}

答案 1 :(得分:-1)

您可以在班级中创建两个这样的属性:

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;
        }
    }
}

您只能映射您的IList属性。