nhibernate - 无法转换类型为 'NHibernate.Collection.Generic.PersistentGenericBag to type ' System.Collections.Generic.List 的对象

标签 nhibernate fluent-nhibernate fluent ilist

我正在尝试通过反序列化 xml 文件来加载域类。所以我在域类中使用了 System.Collections.Generic.List。但是当我尝试使用 Session 对象保存对象时,它失败并出现异常“无法转换类型为'NHibernate.Collection.Generic.PersistentGenericBag 1[MyFirstMapTest.Class5]' to type 'System.Collections.Generic.List1[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,因为它是一个接口(interface)。”

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

我该如何解决这个问题?感谢您关注这个问题。

最佳答案

您可以尝试使用 NHibernte 绑定(bind)的支持字段和序列化的属性,其中属性将是 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; }
    }
}

关于nhibernate - 无法转换类型为 'NHibernate.Collection.Generic.PersistentGenericBag to type ' System.Collections.Generic.List 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16642466/

相关文章:

c# - Nunit 测试 dll,单独运行通过,一起运行第二个失败

c# - 如何创建自定义 NHibernate 配置属性?

NHibernate, "On Delete Cascade",级联删除相关表中的行?

nhibernate - 从多对多关系中删除项目

c# - 无法使用 Nhibernate 为 SQL Server CE 创建架构

.net - 流利的NHibernate +多个数据库

c# - Fluent NHibernate - 应用自定义类型的约定

python - 这里有必要使用 'if'语句吗?

postgresql - Vapor 中的多个数据库

collections - 使用 next() 和 get() 从对象迭代